diff --git a/.env b/.env
index 95dbbc6f1..d7a041f3d 100644
--- a/.env
+++ b/.env
@@ -2,6 +2,9 @@
### The variables set in this file will be taken into account at build time.
###
+### When set to 'true', this variable will enable contract verification UI phase 2
+VITE_APP_ENABLE_VERIFICATION_UI_PHASE2=true
+
### When set to 'true', this variable will enable 'Metamask' support
VITE_APP_ENABLE_METAMASK=true
diff --git a/package-lock.json b/package-lock.json
index cc093488e..d0197b957 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -28,6 +28,7 @@
"crypto-js": "4.1.1",
"ethers": "^5.7.2",
"hashconnect": "^0.1.10",
+ "solc": "^0.8.21",
"vue": "^3.3.4",
"vue-router": "^4.2.5",
"web3-utils": "1.10.0"
@@ -41,6 +42,7 @@
"@vitejs/plugin-basic-ssl": "^1.0.1",
"@vitejs/plugin-vue": "^4.4.0",
"@vitest/coverage-v8": "^0.34.6",
+ "@vitest/web-worker": "^0.34.6",
"@vue/eslint-config-typescript": "^11.0.3",
"@vue/test-utils": "^2.4.1",
"@vue/tsconfig": "^0.4.0",
@@ -58,6 +60,7 @@
"typescript": "~5.0.4",
"vite": "^4.5.0",
"vite-plugin-node-polyfills": "^0.9.0",
+ "vite-plugin-require-transform": "^1.0.21",
"vite-plugin-rewrite-all": "^1.0.1",
"vitest": "^0.34.6",
"vue-tsc": "^1.8.22"
@@ -4870,6 +4873,21 @@
"url": "https://opencollective.com/vitest"
}
},
+ "node_modules/@vitest/web-worker": {
+ "version": "0.34.6",
+ "resolved": "https://registry.npmjs.org/@vitest/web-worker/-/web-worker-0.34.6.tgz",
+ "integrity": "sha512-bSVreTLHgDuwICHvKxl0oi4KfD12ZUX9XYoV+5cyVLB4JWTch0BE2okUr+Z1r2ESpBLrUb2ck8kT7JSEWbCmMg==",
+ "dev": true,
+ "dependencies": {
+ "debug": "^4.3.4"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "vitest": ">=0.34.0"
+ }
+ },
"node_modules/@volar/language-core": {
"version": "1.10.7",
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-1.10.7.tgz",
@@ -6841,6 +6859,11 @@
"node": ">= 0.8"
}
},
+ "node_modules/command-exists": {
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz",
+ "integrity": "sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w=="
+ },
"node_modules/commander": {
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz",
@@ -10948,7 +10971,6 @@
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz",
"integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==",
- "dev": true,
"engines": {
"node": ">= 0.10.0"
}
@@ -11853,6 +11875,14 @@
"integrity": "sha512-gjcpUc3clBf9+210TRaDWbf+rZZZEshZ+DlXMRCeAjp0xhTrnQsKHypIy1J3d5hKdUzj69t708EHtU8P6bUn0A==",
"dev": true
},
+ "node_modules/os-tmpdir": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
+ "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/ospath": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/ospath/-/ospath-1.2.2.tgz",
@@ -13644,6 +13674,53 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
+ "node_modules/solc": {
+ "version": "0.8.22",
+ "resolved": "https://registry.npmjs.org/solc/-/solc-0.8.22.tgz",
+ "integrity": "sha512-bA2tMZXx93R8L5LUH7TlB/f+QhkVyxrrY6LmgJnFFZlRknrhYVlBK1e3uHIdKybwoFabOFSzeaZjPeL/GIpFGQ==",
+ "dependencies": {
+ "command-exists": "^1.2.8",
+ "commander": "^8.1.0",
+ "follow-redirects": "^1.12.1",
+ "js-sha3": "0.8.0",
+ "memorystream": "^0.3.1",
+ "semver": "^5.5.0",
+ "tmp": "0.0.33"
+ },
+ "bin": {
+ "solcjs": "solc.js"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/solc/node_modules/commander": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/solc/node_modules/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/solc/node_modules/tmp": {
+ "version": "0.0.33",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz",
+ "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==",
+ "dependencies": {
+ "os-tmpdir": "~1.0.2"
+ },
+ "engines": {
+ "node": ">=0.6.0"
+ }
+ },
"node_modules/sonic-boom": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.7.0.tgz",
@@ -14940,6 +15017,18 @@
"vite": "^2.0.0 || ^3.0.0 || ^4.0.0"
}
},
+ "node_modules/vite-plugin-require-transform": {
+ "version": "1.0.21",
+ "resolved": "https://registry.npmjs.org/vite-plugin-require-transform/-/vite-plugin-require-transform-1.0.21.tgz",
+ "integrity": "sha512-A3SrHhVg9tCW35O7E8kcuB71YTEdVd3EaM1zh6gbH4zxy4WzXSfcNf0UiWmaHHhr6wdFhiiAGdpR6S0SUxXkGQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/generator": "^7.22.5",
+ "@babel/parser": "^7.22.5",
+ "@babel/traverse": "^7.22.5",
+ "@babel/types": "^7.22.5"
+ }
+ },
"node_modules/vite-plugin-rewrite-all": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/vite-plugin-rewrite-all/-/vite-plugin-rewrite-all-1.0.1.tgz",
diff --git a/package.json b/package.json
index 419e50dfe..b038c53f1 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"crypto-js": "4.1.1",
"ethers": "^5.7.2",
"hashconnect": "^0.1.10",
+ "solc": "^0.8.21",
"vue": "^3.3.4",
"vue-router": "^4.2.5",
"web3-utils": "1.10.0"
@@ -52,6 +53,7 @@
"@vitejs/plugin-basic-ssl": "^1.0.1",
"@vitejs/plugin-vue": "^4.4.0",
"@vitest/coverage-v8": "^0.34.6",
+ "@vitest/web-worker": "^0.34.6",
"@vue/eslint-config-typescript": "^11.0.3",
"@vue/test-utils": "^2.4.1",
"@vue/tsconfig": "^0.4.0",
@@ -69,6 +71,7 @@
"typescript": "~5.0.4",
"vite": "^4.5.0",
"vite-plugin-node-polyfills": "^0.9.0",
+ "vite-plugin-require-transform": "^1.0.21",
"vite-plugin-rewrite-all": "^1.0.1",
"vitest": "^0.34.6",
"vue-tsc": "^1.8.22"
diff --git a/src/assets/file-add.svg b/src/assets/file-add.svg
new file mode 100644
index 000000000..b0ccc594f
--- /dev/null
+++ b/src/assets/file-add.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/src/assets/json-file-grey.svg b/src/assets/json-file-grey.svg
new file mode 100644
index 000000000..b52d6d488
--- /dev/null
+++ b/src/assets/json-file-grey.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/src/assets/json-file.svg b/src/assets/json-file.svg
new file mode 100644
index 000000000..a8532efeb
--- /dev/null
+++ b/src/assets/json-file.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/src/assets/red-trash.svg b/src/assets/red-trash.svg
new file mode 100644
index 000000000..dddb42607
--- /dev/null
+++ b/src/assets/red-trash.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/src/assets/solidity-file.svg b/src/assets/solidity-file.svg
new file mode 100644
index 000000000..dff28c2ae
--- /dev/null
+++ b/src/assets/solidity-file.svg
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/assets/solidity-icon-grey.svg b/src/assets/solidity-icon-grey.svg
new file mode 100644
index 000000000..c968190d7
--- /dev/null
+++ b/src/assets/solidity-icon-grey.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/src/assets/solidity-icon.svg b/src/assets/solidity-icon.svg
new file mode 100644
index 000000000..c44a2fdaf
--- /dev/null
+++ b/src/assets/solidity-icon.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/src/assets/styles/explorer.scss b/src/assets/styles/explorer.scss
index 4ff768a79..1d83155db 100644
--- a/src/assets/styles/explorer.scss
+++ b/src/assets/styles/explorer.scss
@@ -391,6 +391,10 @@ hr.dotted {
margin: 0;
padding: 0;
}
+/* Dashed DnD area */
+.h-dotted-area {
+ border: dashed 1px $h-highlight-color;
+}
//
// MODALS
@@ -523,3 +527,6 @@ table.o-table th.o-table__th--left {
min-height: 450px;
}
+.h-has-page-background {
+ background-color: $h-page-background-color;
+}
diff --git a/src/components/ConfirmDialog.vue b/src/components/ConfirmDialog.vue
index b646924ff..5448a99bf 100644
--- a/src/components/ConfirmDialog.vue
+++ b/src/components/ConfirmDialog.vue
@@ -36,14 +36,14 @@
{{ mainMessage }}
Filler
-
+
{{ extraMessage }}
Filler
- CANCEL
- CONFIRM
+ {{ cancelLabel }}
+ {{ confirmLabel }}
@@ -57,7 +57,7 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/components/verification/ContractVerificationDialog.vue b/src/components/verification/ContractVerificationDialog.vue
new file mode 100644
index 000000000..22323c1ef
--- /dev/null
+++ b/src/components/verification/ContractVerificationDialog.vue
@@ -0,0 +1,469 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ dialogTitle }}
+
+
+ Please upload the Solidity source files and metadata associated with the Hedera contract.
+ Once submitted the verification service will compile the source code and match it with
+ the contract bytecode deployed on the Hedera network.
+
+
+
+
+
+
+ Add files
+
+
+ {{ status }}
+
+
+
+
+
+
+
+ ADD MORE FILES
+
+
+
+
+ CANCEL
+ VERIFY
+
+
+
+
+
+
+
+
+
+ {{ dialogTitle }}
+
+
+
+
+
+
+
+ {{ dialogTitle }}
+
+
+
+
+
+
+
+ {{ dialogTitle }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/components/verification/FileList.vue b/src/components/verification/FileList.vue
new file mode 100644
index 000000000..1646b1540
--- /dev/null
+++ b/src/components/verification/FileList.vue
@@ -0,0 +1,229 @@
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ tableTitle }}
+
+
+
+ {{ isListFiltered ? 'Show unused' : 'Hide unused' }}
+ {{ ' (' + nbUnusedAuditItems + ')' }}
+
+
+ Clear all
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ props.row.path }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/schemas/NetworkRegistry.ts b/src/schemas/NetworkRegistry.ts
index 8c9be10c3..36115130a 100644
--- a/src/schemas/NetworkRegistry.ts
+++ b/src/schemas/NetworkRegistry.ts
@@ -131,10 +131,10 @@ export class SourcifySetup {
return this.serverURL + "files/any/" + this.chainID + "/" + normalizedAddress
}
- makeMetadataURL(contractAddress: string, full: boolean): string {
+ makeContractSourceURL(contractAddress: string, full: boolean): string {
const normalizedAddress = EthereumAddress.normalizeEIP55(contractAddress)
const matchPrefix = full ? "full_match/" : "partial_match/"
- return this.serverURL + matchPrefix + this.chainID + "/" + normalizedAddress + "/metadata.json"
+ return this.repoURL + matchPrefix + this.chainID + "/" + normalizedAddress
}
makeContractLookupURL(contractAddress: string): string {
diff --git a/src/utils/SolidityFileImporter.ts b/src/utils/SolidityFileImporter.ts
new file mode 100644
index 000000000..d67bbfbde
--- /dev/null
+++ b/src/utils/SolidityFileImporter.ts
@@ -0,0 +1,227 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {computed, ref} from "vue";
+import {SolcUtils} from "@/utils/solc/SolcUtils";
+import {SolcMetadata} from "@/utils/solc/SolcMetadata";
+import {HHUtils} from "@/utils/hardhat/HHUtils";
+import {HHMetadata} from "@/utils/hardhat/HHMetadata";
+
+export class SolidityFileImporter {
+
+ public readonly started = ref(false)
+ public readonly files = ref>(new Map())
+ public readonly failure = ref(null)
+
+ //
+ // Public
+ //
+
+ public start(transferList: DataTransferItemList | FileList) {
+ if (this.started.value) {
+ console.log("SolidityFileImporter aborts because it's already importing")
+ } else {
+
+ // DataTransferItemList is reset immediately after drop callback termination
+ // => we copy file system entries before going async
+ const entries: Array = []
+ for (const i of transferList) {
+ if (transferList instanceof FileList) {
+ entries.push(i as File)
+ } else {
+ const e = (i as DataTransferItem).webkitGetAsEntry()
+ if (e !== null) {
+ entries.push(e)
+ }
+ }
+ }
+
+ // Async starts here
+ this.started.value = true
+ const newFiles = new Map()
+ SolidityFileImporter.importEntries(entries, newFiles)
+ .then(() => {
+ this.files.value = mergeMap(this.files.value, newFiles)
+ this.failure.value = null
+
+ })
+ .catch((reason: unknown) => {
+ // this.files.value is left unchanged
+ this.failure.value = reason
+ console.log("SolidityFileImporter.start did crash:" + reason)
+ })
+ .finally( () => {
+ this.started.value = false
+ })
+ }
+ }
+
+ public reset() {
+ this.files.value = new Map()
+ this.failure.value = null
+ }
+
+ public readonly metadataFileCount = computed(() => {
+ let result = 0
+ for (const content of this.files.value.values()) {
+ if (typeof content === "object") {
+ result += 1
+ }
+ }
+ return result
+ })
+
+ //
+ // Private
+ //
+
+ private static async importEntries(entries: Array, output: Map): Promise {
+ for (const e of entries) {
+ if (e instanceof File) {
+ const topFolder = "/"
+ await this.importFile(e, output, topFolder)
+ } else {
+ const topFolder = e.isDirectory ? "/" + e.name + "/" : "/"
+ await this.importEntry(e, output, topFolder)
+ }
+ }
+ }
+
+ private static async importEntry(e: FileSystemEntry, output: Map, topFolder: string): Promise {
+ if (e !== null) {
+ if (e.isFile) {
+ const fileName = e!.name
+ if (hasExtension(fileName, ".sol")) {
+ const path = removeTopFolder(e.fullPath, topFolder)
+ const content = await asyncReadText(e as FileSystemFileEntry)
+ output.set(path, content)
+ } else if (hasExtension(fileName, ".json")) {
+ const path = removeTopFolder(e.fullPath, topFolder)
+ const content = await asyncReadText(e as FileSystemFileEntry)
+ const solcMetadata = SolcUtils.parseSolcMetadata(content)
+ if (solcMetadata !== null) {
+ output.set(path, solcMetadata)
+ } else {
+ const hhMetadata = HHUtils.parseMetadata(content)
+ if (hhMetadata !== null) {
+ output.set(path, hhMetadata)
+ }
+ }
+ }
+ } else if (e.isDirectory) {
+ const d = e as FileSystemDirectoryEntry
+ for (const c of await asyncReadEntries(d)) {
+ const skip = c.name.startsWith(".") || c.name == "node_modules"
+ if (!skip) {
+ await this.importEntry(c, output, topFolder)
+ }
+ }
+ } else {
+ console.log("SolidityFileImporter ignored unexpected FileSystemEntry subclass: " + typeof e)
+ }
+ }
+ }
+
+ private static async importFile(f: File, output: Map, topFolder: string): Promise {
+ if (f !== null) {
+ const fileName = f!.name
+ if (hasExtension(fileName, ".sol")) {
+ const path = removeTopFolder(f.name, topFolder)
+ const content = await asyncReadTextFromFile(f)
+ output.set(path, content)
+ } else if (hasExtension(fileName, ".json")) {
+ const path = removeTopFolder(f.name, topFolder)
+ const content = await asyncReadTextFromFile(f)
+ const solcMetadata = SolcUtils.parseSolcMetadata(content)
+ if (solcMetadata !== null) {
+ output.set(path, solcMetadata)
+ } else {
+ const hhMetadata = HHUtils.parseMetadata(content)
+ if (hhMetadata !== null) {
+ output.set(path, hhMetadata)
+ }
+ }
+ }
+ }
+ }
+}
+
+
+async function asyncReadText(e: FileSystemFileEntry): Promise {
+
+ return new Promise((resolve, reject) => {
+ e.file((file: File) => {
+ resolve(file.text())
+ }, (error: unknown) => {
+ reject(error)
+ })
+ })
+}
+
+async function asyncReadTextFromFile(f: File): Promise {
+ return Promise.resolve(f.text())
+}
+
+async function asyncReadEntries(e: FileSystemDirectoryEntry): Promise {
+ let result: FileSystemEntry[] = [];
+ return new Promise((resolve, reject) => {
+ const reader = e.createReader()
+ const readEntries = () => {
+ reader.readEntries((files: FileSystemEntry[]) => {
+ if (files.length >= 1) {
+ result = result.concat(files)
+ readEntries()
+ } else {
+ resolve(result)
+ }
+ }, (reason: unknown) => {
+ reject(reason)
+ })
+ }
+ readEntries()
+ })
+}
+
+function mergeMap(m1: Map, m2: Map): Map {
+ const result = new Map
+ for (const [p, c] of m1) {
+ result.set(p, c)
+ }
+ for (const [p, c] of m2) {
+ result.set(p, c)
+ }
+ return result
+}
+
+function removeTopFolder(path: string, topFolder: string): string {
+ let result: string
+ if (path.startsWith(topFolder)) {
+ result = path.substring(topFolder.length)
+ } else {
+ result = path
+ }
+ return result
+}
+
+function hasExtension(fileName: string, extension: string): boolean {
+ const n = fileName.toLowerCase()
+ const x = extension.toLowerCase()
+ return n.lastIndexOf(x) == n.length - x.length
+}
diff --git a/src/utils/analyzer/ContractAnalyzer.ts b/src/utils/analyzer/ContractAnalyzer.ts
index 3dabd0dc4..b2c06a51c 100644
--- a/src/utils/analyzer/ContractAnalyzer.ts
+++ b/src/utils/analyzer/ContractAnalyzer.ts
@@ -25,21 +25,17 @@ import {AssetCache} from "@/utils/cache/AssetCache";
import {SourcifyCache, SourcifyRecord} from "@/utils/cache/SourcifyCache";
import {SolcMetadata} from "@/utils/solc/SolcMetadata";
import {ByteCodeAnalyzer} from "@/utils/analyzer/ByteCodeAnalyzer";
-import {ContractSourceAnalyzer} from "@/utils/analyzer/ContractSourceAnalyzer";
import {ContractResponse} from "@/schemas/HederaSchemas";
import {ContractByIdCache} from "@/utils/cache/ContractByIdCache";
-import {AppStorage} from "@/AppStorage";
export class ContractAnalyzer {
- public readonly contractId: Ref
+ public readonly contractId: Ref
public readonly byteCodeAnalyzer: ByteCodeAnalyzer
- private readonly contractResponse: Ref = ref(null)
- private readonly systemContractEntry: Ref = ref(null)
- private readonly localStorageMetadata: Ref = ref(null)
- public readonly sourcifyRecord: Ref = ref(null)
- public readonly missingSourceCount = ref(0)
- private readonly abi: Ref = ref(null)
+ private readonly contractResponse: Ref = ref(null)
+ private readonly systemContractEntry: Ref = ref(null)
+ public readonly sourcifyRecord: Ref = ref(null)
+ private readonly abi: Ref = ref(null)
private watchHandles: WatchStopHandle[] = []
@@ -48,7 +44,7 @@ export class ContractAnalyzer {
// Public
//
- public constructor(contractId: Ref) {
+ public constructor(contractId: Ref) {
this.contractId = contractId
this.byteCodeAnalyzer = new ByteCodeAnalyzer(this.byteCode)
}
@@ -56,10 +52,9 @@ export class ContractAnalyzer {
public mount(): void {
this.byteCodeAnalyzer.mount()
this.watchHandles = [
- watch(this.contractId, this.contractIdDidChange, { immediate: true}),
- watch(this.contractResponse, this.contractResponseDidChange, { immediate: true}),
- watch([this.systemContractEntry, this.metadata], this.updateABI, { immediate: true}),
- watch([this.metadata, this.sourceAnalyzers], this.updateMissingSourceCount, { immediate: true, deep: true}),
+ watch(this.contractId, this.contractIdDidChange, {immediate: true}),
+ watch(this.contractResponse, this.contractResponseDidChange, {immediate: true}),
+ watch([this.systemContractEntry, this.metadata], this.updateABI, {immediate: true}),
]
}
@@ -73,15 +68,13 @@ export class ContractAnalyzer {
this.abi.value = null
}
- public readonly globalState = computed(() => {
- let result: GlobalState|null
+ public readonly globalState = computed(() => {
+ let result: GlobalState | null
if (this.contractId.value !== null) {
if (this.sourcifyRecord.value !== null) {
result = this.sourcifyRecord.value.fullMatch ? GlobalState.FullMatch : GlobalState.PartialMatch
- } else if (this.metadata.value !== null) {
- result = this.missingSourceCount.value >= 1 ? GlobalState.MissingSources : GlobalState.ReadyToVerifiy
} else {
- result = GlobalState.Unknown
+ result = GlobalState.Unverified
}
} else {
result = null
@@ -89,49 +82,18 @@ export class ContractAnalyzer {
return result
})
- public readonly metadata: ComputedRef = computed(() => {
- let result: SolcMetadata|null
+ public readonly metadata: ComputedRef = computed(() => {
+ let result: SolcMetadata | null
if (this.sourcifyRecord.value !== null) {
result = SourcifyCache.fetchMetadata(this.sourcifyRecord.value.response)
- } else if (this.localStorageMetadata.value !== null) {
- result = this.localStorageMetadata.value
- } else if (this.byteCodeAnalyzer.ipfsMetadata.value !== null) {
- result = this.byteCodeAnalyzer.ipfsMetadata.value
} else {
result = null
}
return result
})
- public readonly metadataOrigin: ComputedRef = computed(() => {
- let result: MetadataOrigin|null
- if (this.systemContractEntry.value !== null) {
- result = MetadataOrigin.System
- } else if (this.sourcifyRecord.value !== null) {
- result = MetadataOrigin.Sourcify
- } else if (this.localStorageMetadata.value !== null) {
- result = MetadataOrigin.LocalStorage
- } else if (this.byteCodeAnalyzer.ipfsMetadata.value !== null) {
- result = MetadataOrigin.IPFS
- } else {
- result = null
- }
- return result
- })
-
- public readonly isUnknownContract = computed(
- () => this.metadataOrigin.value === null)
- public readonly isSystemContract = computed(
- () => this.metadataOrigin.value === MetadataOrigin.System)
- public readonly isContractOnSourcify = computed(
- () => this.metadataOrigin.value === MetadataOrigin.Sourcify)
- public readonly isContractOnIPFS = computed(
- () => this.metadataOrigin.value === MetadataOrigin.IPFS)
- public readonly isContractOnLocalStorage = computed(
- () => this.metadataOrigin.value === MetadataOrigin.LocalStorage)
-
- public readonly interface: ComputedRef = computed(() => {
- let result: ethers.utils.Interface|null
+ public readonly interface: ComputedRef = computed(() => {
+ let result: ethers.utils.Interface | null
if (this.abi.value !== null) {
try {
const i = new ethers.utils.Interface(this.abi.value)
@@ -145,8 +107,8 @@ export class ContractAnalyzer {
return result
})
- public readonly sourceFileName: ComputedRef = computed(() => {
- let result: string|null
+ public readonly sourceFileName: ComputedRef = computed(() => {
+ let result: string | null
if (this.systemContractEntry.value !== null) {
result = this.systemContractEntry.value.abiFileName
} else if (this.metadata.value !== null) {
@@ -159,8 +121,8 @@ export class ContractAnalyzer {
return result
})
- public readonly contractName: ComputedRef = computed(() => {
- let result: string|null
+ public readonly contractName: ComputedRef = computed(() => {
+ let result: string | null
if (this.systemContractEntry.value !== null) {
result = null
} else if (this.metadata.value !== null) {
@@ -173,42 +135,40 @@ export class ContractAnalyzer {
return result
})
- public readonly sourceFileNames: ComputedRef = computed(() => {
- let result: string[]
- if (this.systemContractEntry.value !== null) {
- result = []
- } else if (this.metadata.value !== null) {
- const sources = this.metadata.value.sources
- result = Object.keys(sources)
- } else {
- result = []
- }
- return result
- })
-
- public readonly sourceContents: ComputedRef> = computed(() => {
- const result: Record = {}
- for (const f of this.sourceAnalyzers.value) {
- if (f.content.value !== null) {
- result[f.sourceFileName] = f.content.value
- }
+ public readonly sourceFiles = computed(() => {
+ let result: Array = []
+ if (this.sourcifyRecord.value !== null && this.sourcifyRecord.value?.response.files.length > 0) {
+ const files = this.sourcifyRecord.value?.response.files
+ files?.forEach((f) => {
+ const parts = f.name.split('.')
+ const suffix = parts[parts.length - 1].toLowerCase()
+ if (suffix === "sol") {
+ result.push(f.content)
+ }
+ })
}
return result
})
- public readonly sourceAnalyzers: ComputedRef = computed(() => {
- const result: ContractSourceAnalyzer[] = []
- for (const f of this.sourceFileNames.value) {
- result.push(new ContractSourceAnalyzer(f, this))
- }
- return result
- })
+ //
+ // public readonly sourceFileNames: ComputedRef = computed(() => {
+ // let result: string[]
+ // if (this.systemContractEntry.value !== null) {
+ // result = []
+ // } else if (this.metadata.value !== null) {
+ // const sources = this.metadata.value.sources
+ // result = Object.keys(sources).sort()
+ // } else {
+ // result = []
+ // }
+ // return result
+ // })
//
// Public (null if contractId is a system contract)
//
- public readonly byteCode: ComputedRef = computed(() => {
+ public readonly byteCode: ComputedRef = computed(() => {
return this.contractResponse.value?.runtime_bytecode ?? null
})
@@ -216,10 +176,10 @@ export class ContractAnalyzer {
// Public (null if contractId is not on Sourcify)
//
- public readonly fullMatch: ComputedRef = computed(
+ public readonly fullMatch: ComputedRef = computed(
() => this.sourcifyRecord.value?.fullMatch ?? null)
- public readonly sourcifyURL: ComputedRef = computed(
+ public readonly sourcifyURL: ComputedRef = computed(
() => this.sourcifyRecord.value?.folderURL ?? null)
@@ -227,22 +187,6 @@ export class ContractAnalyzer {
// Public (user actions)
//
- public userDidSelectMetadata(metadata: SolcMetadata): void {
- if (this.contractId.value !== null) {
- AppStorage.setMetadata(metadata, this.contractId.value)
- this.updateLocalStorageMetadata()
- }
- // else should not happen
- }
-
- public userRequestClearMetadata(): void {
- if (this.contractId.value !== null) {
- AppStorage.setMetadata(null, this.contractId.value)
- this.updateLocalStorageMetadata()
- }
- // else should not happen
- }
-
public verifyDidComplete(): void {
if (this.contractId.value !== null) {
SourcifyCache.instance.forget(this.contractId.value)
@@ -272,7 +216,6 @@ export class ContractAnalyzer {
this.systemContractEntry.value = null
this.contractResponse.value = null
}
- this.updateLocalStorageMetadata()
}
private contractResponseDidChange = async () => {
@@ -291,48 +234,21 @@ export class ContractAnalyzer {
if (this.systemContractEntry.value !== null) {
try {
const abiURL = this.systemContractEntry.value?.abiURL
- const asset = await AssetCache.instance.lookup(abiURL) as { abi: ethers.utils.Fragment[]}
+ const asset = await AssetCache.instance.lookup(abiURL) as { abi: ethers.utils.Fragment[] }
this.abi.value = asset.abi
} catch {
this.abi.value = null
}
} else if (this.metadata.value !== null) {
- this.abi.value = this.metadata.value.output.abi as ethers.utils.Fragment[]|null
+ this.abi.value = this.metadata.value.output.abi as ethers.utils.Fragment[] | null
} else {
this.abi.value = null
}
}
-
- private readonly updateMissingSourceCount = () => {
- if (this.metadata.value !== null) {
- let newValue = 0
- for (const a of this.sourceAnalyzers.value) {
- if (a.content.value === null) {
- newValue += 1
- }
- }
- this.missingSourceCount.value = newValue
- } else {
- this.missingSourceCount.value = 0
- }
- }
-
- private updateLocalStorageMetadata(): void {
- this.localStorageMetadata.value = this.contractId.value != null ? AppStorage.getMetadata(this.contractId.value) : null
- }
- }
-
-export enum MetadataOrigin {
- System = "System",
- Sourcify = "Sourcify",
- IPFS = "IPFS",
- LocalStorage = "Local Storage",
}
export enum GlobalState {
- Unknown, // Metadata file is missing
- MissingSources, // Metadata file is available but some/all sources are missing
- ReadyToVerifiy, // Metadata file and sources are available but are not verified
FullMatch, // Fully verified on sourcify
PartialMatch, // Partially verified on sourcify
+ Unverified // Unverified
}
\ No newline at end of file
diff --git a/src/utils/analyzer/ContractSourceAnalyzer.ts b/src/utils/analyzer/ContractSourceAnalyzer.ts
index 23c8d5afb..b5aee8a8d 100644
--- a/src/utils/analyzer/ContractSourceAnalyzer.ts
+++ b/src/utils/analyzer/ContractSourceAnalyzer.ts
@@ -18,159 +18,73 @@
*
*/
-import {computed, ref, Ref, WatchStopHandle} from 'vue';
-import {ContractAnalyzer, MetadataOrigin} from "@/utils/analyzer/ContractAnalyzer";
-import {Lookup} from "@/utils/cache/base/EntityCache";
-import {IPFSCache} from "@/utils/cache/IPFSCache";
-import {SolcUtils} from "@/utils/solc/SolcUtils";
-import {SourcifyCache} from "@/utils/cache/SourcifyCache";
-import {AppStorage} from "@/AppStorage";
-import {ethers} from "ethers";
+import {computed, ref, Ref, shallowRef, watch, WatchStopHandle} from 'vue';
+import {ByteCodeAnalyzer} from "@/utils/analyzer/ByteCodeAnalyzer";
+import {SolcMetadata} from "@/utils/solc/SolcMetadata";
+import {ContractSourceAudit} from "@/utils/analyzer/ContractSourceAudit";
+import {HHMetadata} from "@/utils/hardhat/HHMetadata";
export class ContractSourceAnalyzer {
- public readonly sourceFileName: string
- public readonly contractAnalyzer: ContractAnalyzer
- public readonly ipfsLookup: Lookup
- private readonly localStorageContent: Ref = ref(null)
+ public readonly byteCodeAnalyzer: ByteCodeAnalyzer
+ public readonly inputFiles: Ref>
+
+ private readonly analyzingRef = ref(false)
+ private readonly auditRef = shallowRef(null)
private watchHandle: WatchStopHandle|null = null
//
// Public
//
- public constructor(sourceFileName: string, contractAnalyzer: ContractAnalyzer) {
- this.sourceFileName = sourceFileName
- this.contractAnalyzer = contractAnalyzer
- this.ipfsLookup = IPFSCache.instance.makeLookup(this.ipfsHash)
+ public constructor(byteCodeAnalyzer: ByteCodeAnalyzer, inputFiles: Ref>) {
+ this.byteCodeAnalyzer = byteCodeAnalyzer
+ this.inputFiles = inputFiles
}
public mount(): void {
- this.ipfsLookup.mount()
- this.updateLocalStorageContent()
+ this.watchHandle = watch([
+ this.inputFiles,
+ this.byteCodeAnalyzer.byteCode,
+ this.byteCodeAnalyzer.solcVersion], this.updateAudit)
}
public unmount(): void {
- this.ipfsLookup.unmount()
- this.localStorageContent.value = null
if (this.watchHandle !== null) {
this.watchHandle()
this.watchHandle = null
}
+ this.auditRef.value = null
}
//
// Public (computed)
//
- public readonly content = computed(
- () => this.sourcifyContent.value ?? this.localStorageContent.value ?? this.ipfsContent.value)
+ public readonly analyzing = computed( () => this.analyzingRef.value)
- public readonly fullMatch = computed(() => {
- let result: boolean
- if (this.content.value !== null && this.keccakHash.value !== null) {
- const contentBytes = ethers.utils.toUtf8Bytes(this.content.value)
- const contentHash = ethers.utils.keccak256(contentBytes)
- result = contentHash === this.keccakHash.value
- } else {
- result = false
- }
- return result
- })
-
- public readonly origin = computed(() => {
- let result: MetadataOrigin|null
- if (this.sourcifyContent.value !== null) {
- result = MetadataOrigin.Sourcify
- } else if (this.localStorageContent.value !== null) {
- result = MetadataOrigin.LocalStorage
- } else if (this.ipfsContent.value !== null) {
- result = MetadataOrigin.IPFS
- } else {
- result = null
- }
- return result
- })
-
- //
- // Public (user actions)
- //
-
- public userDidSelectContent(content: string): void {
- AppStorage.setSource(content, this.sourceFileName)
- this.updateLocalStorageContent()
- }
-
- public userRequestClear(): void {
- AppStorage.setSource(null, this.sourceFileName)
- this.updateLocalStorageContent()
- }
+ public readonly audit = computed(() => this.auditRef.value)
//
// Private
//
- private readonly sourcifyContent = computed(() => {
- let result: string|null
- const response = this.contractAnalyzer.sourcifyRecord.value?.response ?? null
- if (response !== null) {
- result = SourcifyCache.fetchSource(this.sourceBaseName(), response)
- } else {
- result = null
- }
- return result
- })
-
- private readonly ipfsContent = computed(() => {
- let result: string|null
- const content = this.ipfsLookup.entity.value
- if (typeof content == "string") {
- result = content
- } else if (typeof content === "object" && content !== null) {
- result = JSON.stringify(content)
- } else {
- result = null
- }
- return result
- })
-
- private readonly ipfsHash = computed(() => {
- let result: string|null
- if (this.contractAnalyzer.metadata.value !== null) {
- result = SolcUtils.fetchIPFSHash(this.sourceFileName, this.contractAnalyzer.metadata.value)
- } else {
- result = null
- }
- return result
- })
-
- private readonly swarmHash = computed(() => {
- let result: string|null
- if (this.contractAnalyzer.metadata.value !== null) {
- result = SolcUtils.fetchSWARMHash(this.sourceFileName, this.contractAnalyzer.metadata.value)
+ private readonly updateAudit = async () => {
+ const inputFiles = this.inputFiles.value
+ const solcVersion = this.byteCodeAnalyzer.solcVersion.value
+ const byteCode = this.byteCodeAnalyzer.byteCode.value
+ if (inputFiles.size >= 1 && solcVersion !== null && byteCode !== null) {
+ this.analyzingRef.value = true
+ try {
+ this.auditRef.value = await ContractSourceAudit.build(this.inputFiles.value, solcVersion, byteCode)
+ } finally {
+ this.analyzingRef.value = false
+ }
} else {
- result = null
+ this.auditRef.value = null
}
- return result
- })
-
- private readonly keccakHash = computed(() => {
- let result: string|null
- if (this.contractAnalyzer.metadata.value !== null) {
- result = SolcUtils.fetchKeccakHash(this.sourceFileName, this.contractAnalyzer.metadata.value)
- } else {
- result = null
- }
- return result
- })
-
- private readonly updateLocalStorageContent = () => {
- this.localStorageContent.value = AppStorage.getSource(this.sourceFileName)
}
- private sourceBaseName(): string {
- const i = this.sourceFileName.lastIndexOf("/")
- return i != -1 ? this.sourceFileName.substring(i+1) : this.sourceFileName
- }
-}
\ No newline at end of file
+}
+
diff --git a/src/utils/analyzer/ContractSourceAudit.ts b/src/utils/analyzer/ContractSourceAudit.ts
new file mode 100644
index 000000000..125daa08c
--- /dev/null
+++ b/src/utils/analyzer/ContractSourceAudit.ts
@@ -0,0 +1,610 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {ContractRecord, SolcReport, SolcUtils} from "@/utils/solc/SolcUtils";
+import {SolcMetadata} from "@/utils/solc/SolcMetadata";
+import {SolcIndexCache} from "@/utils/cache/SolcIndexCache";
+import {InputSettings, SolcInput} from "@/utils/solc/SolcInput";
+import {HHMetadata} from "@/utils/hardhat/HHMetadata";
+import {HHMatch, HHUtils} from "@/utils/hardhat/HHUtils";
+
+export enum ContractAuditStatus {
+ NoSourceFile,
+ Failure, // failure !== null
+ UnknownCompilerVersion,
+ CompilationErrors, // longCompilerversion !== null
+ Unresolved, // longCompilerVersion !== null
+ Resolved, // longCompilerversion !== null && resolvedMetadata !== null // contractRecord may be null
+}
+
+export enum ContractAuditItemStatus {
+ OK,
+ Unused,
+ Unknown,
+}
+
+export class ContractAuditItem {
+
+ public readonly path: string
+ public readonly content: string | SolcMetadata | SolcInput | HHMetadata
+ public readonly status: ContractAuditItemStatus
+ public readonly target: boolean
+
+ constructor(path: string, content: string | SolcMetadata | SolcInput | HHMetadata, status: ContractAuditItemStatus, target: boolean) {
+ this.path = path
+ this.content = content
+ this.status = status
+ this.target = target
+ }
+}
+
+export class ContractSourceAudit {
+
+ public readonly status: ContractAuditStatus
+ public readonly items: ContractAuditItem[]
+ public readonly longCompilerVersion: string | null
+ public readonly resolvedContractName: string | null
+ public readonly resolvedMetadata: SolcMetadata | SolcInput | null
+ public readonly missingFiles: string[]
+ public readonly failure: unknown
+
+ //
+ // Public
+ //
+
+ static async build(files: Map, solcVersion: string, deployedByteCode: string): Promise {
+
+ // 1) Let's try with Hard Hat metadata files
+ let result = await this.tryWithHHMetadata(files, deployedByteCode)
+ if (result === null) {
+
+ // We'll need the compiler now
+ const longCompilerVersion = await SolcIndexCache.instance.fetchLongVersion(solcVersion)
+ if (longCompilerVersion !== null) {
+
+ // 2) Let's try with solc input files
+ result = await this.tryWithSolcInput(files, longCompilerVersion, deployedByteCode)
+
+ // We'll need source files now
+ const sourceFiles = new Map()
+ for (const [file, content] of files) {
+ if (typeof content == "string") {
+ sourceFiles.set(file, content)
+ }
+ }
+
+ if (sourceFiles.size >= 1) {
+
+ try {
+ // Let's compile all sources a first time to see if there's any compilation errors or missing file
+ const solcInput = this.makeSolcInput(sourceFiles)
+ const solcReport = await this.compile(solcInput, longCompilerVersion)
+
+ if (SolcUtils.countErrors(solcReport.output) >= 1) {
+ // There a compilation errors
+
+ result = new ContractSourceAudit(
+ ContractAuditStatus.CompilationErrors,
+ ContractSourceAudit.makeAuditItems(files),
+ null,
+ null,
+ null,
+ SolcUtils.fetchMissingFiles(solcReport.output))
+
+ } else {
+
+ if (result === null) {
+ // 3) Let's try with solc metadata files
+ result = await this.tryWithSolcMetadata(files, sourceFiles, longCompilerVersion, deployedByteCode)
+ }
+
+ if (result == null) {
+ // 4) Let's with the source files only
+ result = await this.tryWithSourceFilesOnly(files, solcInput, solcReport, longCompilerVersion, deployedByteCode)
+ }
+ }
+ } catch(reason) {
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Failure,
+ ContractSourceAudit.makeAuditItems(files),
+ null,
+ null,
+ null,
+ [],
+ reason)
+ }
+
+ } else {
+
+ // We need at least one solidity source
+ result = new ContractSourceAudit(
+ ContractAuditStatus.NoSourceFile,
+ ContractSourceAudit.makeAuditItems(files))
+ }
+
+ } else {
+
+ // We did not find solc version in compiler version registry
+ result = new ContractSourceAudit(
+ ContractAuditStatus.UnknownCompilerVersion,
+ ContractSourceAudit.makeAuditItems(files))
+ }
+ }
+
+ return Promise.resolve(result)
+ }
+
+ makeReducedSourceFiles(): Map {
+ const result = new Map()
+ for (const i of this.items) {
+ if (typeof i.content == "string" && i.status !== ContractAuditItemStatus.Unused) {
+ result.set(i.path, i.content)
+ }
+ }
+ return result
+ }
+
+ countMetadataFiles(): number {
+ let result = 0
+ for (const i of this.items) {
+ if (typeof i.content != "string") {
+ result += 1
+ }
+ }
+ return result
+ }
+
+ //
+ // Private (tryWithHHMetadata)
+ //
+
+ private static async tryWithHHMetadata(files: Map,
+ deployedByteCode: string): Promise {
+ let result: ContractSourceAudit|null
+
+ // Extracts HardHat metadata files
+ const hhMetadataFiles = new Map()
+ for (const [file, content] of files) {
+ const hhMetadata = HHUtils.castMetadata(content)
+ if (hhMetadata !== null) {
+ hhMetadataFiles.set(file, hhMetadata)
+ }
+ }
+
+ // Searches HardHat metadata files for a contract matching deployed bytecode
+ const hhMatch = HHUtils.match(deployedByteCode, hhMetadataFiles)
+ if (hhMatch !== null) {
+ // Some bytecode in HardHat metadata match :)
+ const items = ContractSourceAudit.makeAuditItemsWithHHMatch(files, hhMatch)
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Resolved,
+ items,
+ hhMatch.solcLongVersion,
+ hhMatch.contractName,
+ hhMatch.solcInput)
+ } else {
+ result = null
+ }
+
+ return Promise.resolve(result)
+ }
+
+
+ //
+ // Private (tryWithSolcInput)
+ //
+
+ private static async tryWithSolcInput(files: Map,
+ longCompilerVersion: string,
+ deployedByteCode: string): Promise {
+ let result: ContractSourceAudit|null
+
+ // Extracts solc input files
+ const solcInputFiles = new Map()
+ for (const [file, content] of files) {
+ const solcInput = SolcUtils.castSolcInput(content)
+ if (solcInput !== null) {
+ solcInputFiles.set(file, solcInput)
+ }
+ }
+
+ // Compile sources with each solc input file and searches a contract matching deployed bytecode
+ let record: ContractRecord|null = null
+ let solcInput: [string, SolcInput]|null = null
+ let solcReport: SolcReport|null = null
+ for (const [file, content] of solcInputFiles) {
+ try {
+ solcReport = await this.compile(content, longCompilerVersion)
+ if (solcReport !== null) {
+ const r = SolcUtils.findMatchingContract(deployedByteCode, solcReport.output)
+ if (r !== null) {
+ record = r
+ solcInput = [file, content]
+ break
+ }
+ }
+ } catch {}
+ }
+
+ if (record !== null && solcInput !== null && solcReport !== null) {
+ const items = ContractSourceAudit.makeAuditItemsWithMetadata(files, record, solcInput, solcReport)
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Resolved,
+ items,
+ longCompilerVersion,
+ record.contractName,
+ solcInput[1])
+ } else {
+ result = null
+ }
+
+ return Promise.resolve(result)
+ }
+
+ //
+ // Private (tryWithSolcMetadata)
+ //
+
+ private static async tryWithSolcMetadata(files: Map,
+ sourceFiles: Map,
+ longCompilerVersion: string,
+ deployedByteCode: string): Promise {
+ let result: ContractSourceAudit|null
+
+ // Extracts solc metadata files
+ const solcMetadataFiles = new Map()
+ for (const [file, content] of files) {
+ const solcMetadata = SolcUtils.castSolcMetadata(content)
+ if (solcMetadata !== null) {
+ solcMetadataFiles.set(file, solcMetadata)
+ }
+ }
+
+ // Extracts compilation settings from solc metadata files
+ const compilationSettings = new Set()
+ for (const solcMetadata of solcMetadataFiles.values()) {
+ const settings = JSON.stringify(this.makeSolcInputSettings(solcMetadata))
+ compilationSettings.add(settings)
+ }
+
+ // Compiles sources using each settings and searches a contract matching deployed bytecode
+ let record: ContractRecord|null = null
+ let solcReport: SolcReport|null = null
+ for (const settings of compilationSettings) {
+ const input = this.makeSolcInput(sourceFiles, JSON.parse(settings))
+ const report = await this.compile(input, longCompilerVersion)
+ if (report !== null) {
+ const r = SolcUtils.findMatchingContract(deployedByteCode, report.output)
+ if (r !== null) {
+ record = r
+ solcReport = report
+ break
+ }
+ }
+ }
+
+ // Finds matching solc metadata
+ let solcMetadata: [string, SolcMetadata]|null = null
+ if (record !== null && solcReport !== null) {
+ for (const [file, content] of solcMetadataFiles) {
+ const compilationTarget = SolcUtils.fetchCompilationTarget(content)
+ if (compilationTarget == record.contractName) {
+ solcMetadata = [file, content]
+ }
+ }
+ }
+
+ if (record !== null && solcReport !== null && solcMetadata !== null) {
+
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Resolved,
+ ContractSourceAudit.makeAuditItemsWithMetadata(files, record, solcMetadata, solcReport),
+ longCompilerVersion,
+ record.contractName,
+ solcMetadata[1])
+
+ } else {
+ result = null
+ }
+
+ return Promise.resolve(result)
+ }
+
+
+ //
+ // Private (tryWithSourceFilesOnly)
+ //
+
+ private static async tryWithSourceFilesOnly(files: Map,
+ solcInput: SolcInput,
+ solcReport: SolcReport,
+ longCompilerVersion: string,
+ deployedByteCode: string): Promise {
+
+ let result: ContractSourceAudit|null
+
+ const record = SolcUtils.findMatchingContract(deployedByteCode, solcReport.output)
+ if (record !== null) {
+ // We found a matching contract using default compiler options ... lucky
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Resolved,
+ ContractSourceAudit.makeAuditItemsWithMetadata(files, record, [record.sourceFileName, solcInput], solcReport),
+ longCompilerVersion,
+ record.contractName,
+ solcInput)
+ } else {
+ const fallbackMetadata = this.findFallbackMetadata(files)
+ if (fallbackMetadata !== null) {
+ // Let's fallback with the metadata file
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Resolved,
+ ContractSourceAudit.makeAuditItemsWithMetadata(files, null, fallbackMetadata, solcReport),
+ longCompilerVersion,
+ null,
+ fallbackMetadata[1])
+ } else {
+ // User action is needed
+ // - either there is no metadata => provide compilation settings
+ // - either there are multiple metadata => identify which one to use
+ result = new ContractSourceAudit(
+ ContractAuditStatus.Unresolved,
+ ContractSourceAudit.makeAuditItems(files),
+ longCompilerVersion)
+ }
+ }
+
+ return Promise.resolve(result)
+ }
+
+ private static findFallbackMetadata(files: Map): [string, SolcMetadata|SolcInput] |null {
+
+ // Splits metadata files by type
+ const hhMetadataFiles = new Map()
+ const solcInputFiles = new Map()
+ const solcMetadataFiles = new Map()
+ for (const [file, content] of files) {
+ const hhMetadata = HHUtils.castMetadata(content)
+ if (hhMetadata !== null) {
+ hhMetadataFiles.set(file, hhMetadata)
+ } else {
+ const solcInput = SolcUtils.castSolcInput(content)
+ if (solcInput !== null) {
+ solcInputFiles.set(file, solcInput)
+ } else {
+ const solcMetadata = SolcUtils.castSolcMetadata(content)
+ if (solcMetadata !== null) {
+ solcMetadataFiles.set(file, solcMetadata)
+ }
+ }
+ }
+ }
+
+ let result: [string, SolcMetadata|SolcInput] | null
+ const metadataFileCount = hhMetadataFiles.size + solcInputFiles.size + solcMetadataFiles.size
+ if (metadataFileCount === 1) {
+ if (hhMetadataFiles.size == 1) {
+ const hhMetadata = hhMetadataFiles.entries().next().value as [string, HHMetadata]
+ result = [hhMetadata[0], hhMetadata[1].input]
+ } else if (solcInputFiles.size == 1) {
+ result = solcInputFiles.entries().next().value
+ } else {
+ result = solcMetadataFiles.entries().next().value
+ }
+ } else {
+ result = null
+ }
+
+ return result
+ }
+
+
+ //
+ // Private
+ //
+
+ private static async compile(solcInput: SolcInput, longCompilerVersion: string): Promise {
+ return await SolcUtils.runAsWorker("v" + longCompilerVersion, solcInput)
+ }
+
+
+ private static makeSolcInput(sourceFiles: Map, settings: InputSettings|null = null): SolcInput {
+ const result: SolcInput = {
+ language: "Solidity",
+ sources: {} as Record,
+ }
+ if (settings !== null) {
+ result.settings = settings
+ result.settings.outputSelection = {
+ '*': {
+ '*': ["metadata", "evm.deployedBytecode.object"],
+ },
+ }
+ } else {
+ result.settings = {
+ outputSelection: {
+ '*': {
+ '*': ["metadata", "evm.deployedBytecode.object"],
+ },
+ },
+ }
+ }
+ for (const [path, content] of sourceFiles) {
+ result.sources[path] = {content: content}
+ }
+ return result
+ }
+
+ private static isReferencedInMetadata(path: string, metadata: SolcMetadata|SolcInput|HHMetadata): boolean {
+ let result: boolean
+ const solcMetadata = SolcUtils.castSolcMetadata(metadata)
+ if (solcMetadata !== null) {
+ result = this.resolvePath(path, solcMetadata) !== null
+ } else {
+ const solcInput = SolcUtils.castSolcInput(metadata)
+ if (solcInput !== null) {
+ result = this.resolvePath(path, solcInput) !== null
+ } else {
+ const hhMetadata = HHUtils.castMetadata(metadata)
+ if (hhMetadata !== null && hhMetadata.input) {
+ result = this.resolvePath(path, hhMetadata.input) !== null
+ } else {
+ result = false
+ }
+ }
+ }
+ return result
+ }
+
+ private static makeSolcInputSettings(solcMetadata: SolcMetadata): InputSettings {
+
+ /*
+ solc metadata solc input settings
+
+ compilationTarget x
+ emVersion x x
+ libraries x x
+ metadata x x
+ optimizer x x
+ outputSelection x
+ remappings x x
+ */
+
+ const result = JSON.parse(JSON.stringify(solcMetadata.settings))
+ delete result.compilationTarget
+ return result
+ }
+
+
+ //
+ // Private
+ //
+
+ private constructor(status: ContractAuditStatus,
+ items: ContractAuditItem[],
+ longCompilerVersion: string | null = null,
+ contractName: string | null = null,
+ resolvedMetadata: SolcMetadata|SolcInput|null = null,
+ missingFiles: string[] = [],
+ failure: unknown = null) {
+ this.status = status
+ this.items = items
+ this.longCompilerVersion = longCompilerVersion
+ this.resolvedContractName = contractName
+ this.resolvedMetadata = resolvedMetadata
+ this.missingFiles = missingFiles
+ this.failure = failure
+ }
+
+ private static makeAuditItemsWithHHMatch(inputFiles: Map,
+ hhMatch: HHMatch): ContractAuditItem[] {
+ const result: ContractAuditItem[] = []
+ for (const [f, c] of inputFiles) {
+ let newItem: ContractAuditItem
+ const hhMetadata = HHUtils.castMetadata(c)
+ if (hhMetadata !== null && f == hhMatch.metadataPath) {
+ newItem = new ContractAuditItem(f, c, ContractAuditItemStatus.OK, true)
+ } else {
+ newItem = new ContractAuditItem(f, c, ContractAuditItemStatus.Unused, false)
+ }
+ result.push(newItem)
+ }
+ return result
+ }
+
+ private static makeAuditItemsWithMetadata(inputFiles: Map,
+ contractRecord: ContractRecord | null = null,
+ resolvedMetadata: [string, SolcMetadata|SolcInput],
+ solcReport: SolcReport): ContractAuditItem[] {
+ const result: ContractAuditItem[] = []
+ const contractDropPath = contractRecord !== null ? this.importToDropPath(contractRecord.sourceFileName, solcReport) : null
+ for (const [f, c] of inputFiles) {
+ let newItem: ContractAuditItem
+ if (typeof c == "string") {
+ // f is a solidity source
+ const target = f == contractDropPath
+ const referenced = this.isReferencedInMetadata(f, resolvedMetadata[1])
+ const status = referenced ? ContractAuditItemStatus.OK : ContractAuditItemStatus.Unused
+ newItem = new ContractAuditItem(f, c, status, target)
+ } else {
+ // f is a metadata file
+ const target = f == resolvedMetadata[0]
+ const itemStatus = target ? ContractAuditItemStatus.OK : ContractAuditItemStatus.Unused
+ newItem = new ContractAuditItem(f, c, itemStatus, target)
+ }
+ result.push(newItem)
+ }
+ return result
+ }
+
+ private static makeAuditItems(inputFiles: Map): ContractAuditItem[] {
+ const result: ContractAuditItem[] = []
+ for (const [f, c] of inputFiles) {
+ result.push(new ContractAuditItem(f, c, ContractAuditItemStatus.Unknown, false))
+ }
+ return result
+ }
+
+ private static importToDropPath(importPath: string, solcReport: SolcReport): string {
+ return solcReport.resolution[importPath] ?? importPath
+ }
+
+ private static resolvePath(path: string, input: SolcMetadata|SolcInput): string|null {
+ let result: string|null
+ if (path in input.sources) {
+ result = path
+ } else {
+ result = null
+ const targets = Object.keys(input.sources)
+ for (const t of targets) {
+ if (this.pathEndsWith(t, path)) {
+ result = t
+ break
+ }
+ }
+ if (result == null) {
+ const i = path.lastIndexOf("/")
+ if (i != -1) {
+ const fileName = path.substring(i+1)
+ for (const t of targets) {
+ if (this.pathEndsWith(t, fileName)) {
+ result = t
+ break
+ }
+ }
+ }
+ }
+ }
+ return result
+ }
+
+ private static pathEndsWith(path: string, suffix: string): boolean {
+ let result: boolean
+ if (path == suffix) {
+ result = true
+ } else if (path.length > suffix.length) {
+ const ss1 = "/" + suffix
+ const ss2 = path.substring(path.length - ss1.length)
+ result = ss1 == ss2
+ } else {
+ result = false
+ }
+ return result
+ }
+}
\ No newline at end of file
diff --git a/src/utils/cache/CacheUtils.ts b/src/utils/cache/CacheUtils.ts
index 21315497f..8ebfef6d6 100644
--- a/src/utils/cache/CacheUtils.ts
+++ b/src/utils/cache/CacheUtils.ts
@@ -65,6 +65,7 @@ export class CacheUtils {
HbarPriceCache.instance.clear()
// IPFSCache.instance => no clear: we preserve it because IPFS content is valid for all networks
NetworkCache.instance.clear()
+ // SolcIndexCache.instance => no clear: solidity compiler index is valid for all networks
SourcifyCache.instance.clear()
StakeCache.instance.clear()
TokenAssociationCache.instance.clear()
diff --git a/src/utils/cache/SolcIndexCache.ts b/src/utils/cache/SolcIndexCache.ts
new file mode 100644
index 000000000..9612d1cb2
--- /dev/null
+++ b/src/utils/cache/SolcIndexCache.ts
@@ -0,0 +1,74 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2022 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {SingletonCache} from "@/utils/cache/base/SingletonCache";
+import axios from "axios";
+import {SolcIndex} from "@/utils/solc/SolcIndex";
+
+export class SolcIndexCache extends SingletonCache {
+
+ public static readonly instance = new SolcIndexCache()
+
+ //
+ // Public
+ //
+
+ public async fetchLongVersion(version: string): Promise {
+
+ /*
+ {
+ "path": "soljson-v0.8.18+commit.87f61d96.js",
+ "version": "0.8.18",
+ "build": "commit.87f61d96",
+ "longVersion": "0.8.18+commit.87f61d96",
+ "keccak256": "0x9a8fa4183ef95496045189b80dfb39f745db89a903b398e40131f500953e5d57",
+ "sha256": "0xd82bdcba2c386d60b33aca148a9cfdf097551f68c5e45d8ec01aebbafacf5075",
+ "urls": [
+ "bzzr://338117c2130fcb6bce3006330712b6e7ee99875b56ce4bb6182312f76e4a6bac",
+ "dweb:/ipfs/QmcKzrqRBy7PeFQxzJDs1AZZzNHKaKbJces6zUDysXZofJ"
+ ]
+ },
+
+ */
+
+ let result: string|null = null
+
+ const index = await this.lookup()
+ if (version in index.releases) {
+ const path = index.releases[version]
+ for (const b of index.builds) {
+ if (b.path == path) {
+ result = b.longVersion
+ break
+ }
+ }
+ }
+
+ return result
+ }
+
+ //
+ // Cache
+ //
+
+ protected async load(): Promise {
+ return (await axios.get("https://binaries.soliditylang.org/bin/list.json")).data
+ }
+}
diff --git a/src/utils/cache/SourcifyCache.ts b/src/utils/cache/SourcifyCache.ts
index 471146ca7..cfee31c1c 100644
--- a/src/utils/cache/SourcifyCache.ts
+++ b/src/utils/cache/SourcifyCache.ts
@@ -82,8 +82,9 @@ export class SourcifyCache extends EntityCache {
const requestURL = sourcifySetup.makeRequestURL(contractAddress)
try {
const response = await axios.get(requestURL)
- const repoURL = sourcifySetup.makeContractLookupURL(contractAddress)
- result = new SourcifyRecord(response.data, response.data.status === "full", repoURL)
+ const isFullMatch = response.data.status === "full"
+ const repoURL = sourcifySetup.makeContractSourceURL(contractAddress, isFullMatch)
+ result = new SourcifyRecord(response.data, isFullMatch, repoURL)
} catch(error) {
if (axios.isAxiosError(error) && error.response?.status == 404) {
result = null
diff --git a/src/utils/hardhat/HHMetadata.ts b/src/utils/hardhat/HHMetadata.ts
new file mode 100644
index 000000000..caea51694
--- /dev/null
+++ b/src/utils/hardhat/HHMetadata.ts
@@ -0,0 +1,45 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2022 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+/*
+ {
+ "id": "759551f1ce3dc2f5642a2c18c92437f1",
+ "_format": "hh-sol-build-info-1",
+ "solcVersion": "0.8.19",
+ "solcLongVersion": "0.8.19+commit.7dd6d404",
+ "input": { ... },
+ "output": { ... },
+ }
+ */
+
+import {SolcInput} from "@/utils/solc/SolcInput";
+import {SolcOutput} from "@/utils/solc/SolcOutput";
+
+export interface HHMetadata {
+
+ id: string
+ _format: unknown[]
+ solcVersion: string
+ solcLongVersion: string
+ input: SolcInput
+ output: SolcOutput
+
+}
diff --git a/src/utils/hardhat/HHUtils.ts b/src/utils/hardhat/HHUtils.ts
new file mode 100644
index 000000000..d1ef7e0c8
--- /dev/null
+++ b/src/utils/hardhat/HHUtils.ts
@@ -0,0 +1,91 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2022 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {HHMetadata} from "@/utils/hardhat/HHMetadata";
+import {SolcInput} from "@/utils/solc/SolcInput";
+import {SolcUtils} from "@/utils/solc/SolcUtils";
+
+export class HHUtils {
+
+ public static castMetadata(content: unknown): HHMetadata|null {
+ let result: HHMetadata|null
+ /*
+
+ {
+ "id": "759551f1ce3dc2f5642a2c18c92437f1",
+ "_format": "hh-sol-build-info-1",
+ "solcVersion": "0.8.19",
+ "solcLongVersion": "0.8.19+commit.7dd6d404",
+ "input": { ... },
+ "output": { ... },
+ }
+
+ */
+
+ if (typeof content === "object" && content !== null) {
+ const ok1 = "id" in content && typeof content.id == "string"
+ const ok2 = "_format" in content && content._format == "hh-sol-build-info-1"
+ const ok3 = "solcVersion" in content && typeof content.solcVersion == "string"
+ const ok4 = "solcLongVersion" in content && typeof content.solcLongVersion == "string"
+ const ok5 = "input" in content && typeof content.input == "object"
+ const ok6 = "output" in content && typeof content.output == "object"
+ result = ok1 && ok2 && ok3 && ok4 && ok5 && ok6 ? content as HHMetadata : null
+ } else {
+ result = null
+ }
+ return result
+ }
+
+ public static parseMetadata(content: string): HHMetadata|null {
+ let result: HHMetadata|null
+ try {
+ const json = JSON.parse(content)
+ result = this.castMetadata(json)
+ } catch {
+ result = null
+ }
+ return result
+ }
+
+
+ public static match(deployedByteCode: string, metadataFiles: Map): HHMatch|null {
+ let result: HHMatch|null = null
+ for (const [file, content] of metadataFiles) {
+ const record = SolcUtils.findMatchingContract(deployedByteCode, content.output)
+ if (record !== null) {
+ result = {
+ contractName: record.contractName,
+ metadataPath: file,
+ solcInput: content.input,
+ solcLongVersion: content.solcLongVersion
+ }
+ break
+ }
+ }
+ return result
+ }
+}
+
+export interface HHMatch {
+ contractName: string
+ metadataPath: string
+ solcInput: SolcInput
+ solcLongVersion: string
+}
diff --git a/src/utils/solc/SolcIndex.ts b/src/utils/solc/SolcIndex.ts
new file mode 100644
index 000000000..8c66f203a
--- /dev/null
+++ b/src/utils/solc/SolcIndex.ts
@@ -0,0 +1,37 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2022 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+export interface SolcIndex {
+ builds: CompilerBuild[]
+ releases: Record
+ latestRelease: string
+}
+
+export interface CompilerBuild {
+ path: string
+ version: string
+ prerelease?: string
+ build: string
+ longVersion: string
+ keccak256: string
+ sha256: string
+ urls: string[]
+}
diff --git a/src/utils/solc/SolcInput.ts b/src/utils/solc/SolcInput.ts
new file mode 100644
index 000000000..cbe9c4963
--- /dev/null
+++ b/src/utils/solc/SolcInput.ts
@@ -0,0 +1,74 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2022 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/*
+ Reference documents:
+
+ https://docs.soliditylang.org/en/latest/using-the-compiler.html#
+
+ */
+
+export interface SolcInput {
+
+ // Reference
+ // https://docs.soliditylang.org/en/latest/using-the-compiler.html#input-description
+
+ // Required: Source code language. Currently supported are "Solidity" and "Yul".
+ language: string,
+
+ // Required
+ sources: Record
+
+ // Optional
+ settings?: InputSettings
+}
+
+export interface SourceInput {
+ keccak256?: string
+ urls?: string[]
+ content?: string
+}
+
+export interface InputSettings {
+ remappings?: string[]
+ outputSelection: Record>
+ optimizer?: {
+ details?: {
+ constantOptimizer?: boolean,
+ cse?: boolean,
+ deduplicate?: boolean,
+ // inliner defaults to "true"
+ inliner?: boolean,
+ // jumpdestRemover defaults to "true"
+ jumpdestRemover?: boolean,
+ orderLiterals?: boolean,
+ // peephole defaults to "true"
+ peephole?: boolean,
+ yul?: boolean,
+ // Optional: Only present if "yul" is "true"
+ yulDetails?: {
+ optimizerSteps?: string,
+ stackAllocation?: boolean
+ }
+ },
+ enabled?: boolean,
+ runs?: number
+ }
+}
diff --git a/src/utils/solc/SolcOutput.ts b/src/utils/solc/SolcOutput.ts
new file mode 100644
index 000000000..9b7bb6f1c
--- /dev/null
+++ b/src/utils/solc/SolcOutput.ts
@@ -0,0 +1,86 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2022 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/*
+ Reference documents:
+
+ https://docs.soliditylang.org/en/latest/using-the-compiler.html#
+
+ */
+
+export interface SolcOutput {
+
+ // Optional: not present if no errors/warnings/infos were encountered
+ errors?: ErrorDescription[]
+ // This contains the contract-level outputs.
+ // It can be limited/filtered by the outputSelection settings.
+ contracts?: Record>
+}
+
+
+export interface ErrorDescription {
+ // Optional: Location within the source file.
+ sourceLocation?: SourceLocation
+ // Optional: Further locations (e.g. places of conflicting declarations)
+ secondarySourceLocations?: SourceLocation
+ // Mandatory: Error type, such as "TypeError", "InternalCompilerError", "Exception", etc.
+ // See below for complete list of types.
+ type: string,
+ // Mandatory: Component where the error originated, such as "general", "ewasm", etc.
+ component: string,
+ // Mandatory ("error", "warning" or "info", but please note that this may be extended in the future)
+ severity: string,
+ // Optional: unique code for the cause of the error
+ errorCode?: string,
+ // Mandatory
+ message: string,
+ // Optional: the message formatted with source location
+ formattedMessage?: string
+}
+
+export interface SourceLocation {
+ file: string,
+ start: number,
+ end: number
+}
+
+export interface ContractDescription {
+ // The Ethereum Contract ABI. If empty, it is represented as an empty array.
+ // See https://docs.soliditylang.org/en/develop/abi-spec.html
+ abi?: [],
+ // EVM-related outputs
+ evm?: EvmDescription
+}
+
+export interface EvmDescription {
+ bytecode: BytecodeDescription
+ deployedBytecode: BytecodeDescription,
+}
+
+export interface BytecodeDescription {
+ // The bytecode as a hex string.
+ object: string
+}
+
+
+//
+// Tools
+//
+
diff --git a/src/utils/solc/SolcUtils.ts b/src/utils/solc/SolcUtils.ts
index a17b7cddc..6f96434cf 100644
--- a/src/utils/solc/SolcUtils.ts
+++ b/src/utils/solc/SolcUtils.ts
@@ -19,9 +19,82 @@
*/
import {SolcMetadata} from "@/utils/solc/SolcMetadata";
+import {SolcInput} from "@/utils/solc/SolcInput";
+import {ContractDescription, SolcOutput} from "@/utils/solc/SolcOutput";
+import {splitAuxdata} from "@ethereum-sourcify/bytecode-utils";
export class SolcUtils {
+ public static async runAsWorker(version: string, input: SolcInput): Promise {
+ const worker = new Worker(new URL("./SolcWorker.ts", import.meta.url), { type: "classic"})
+ return new Promise((resolve, reject) => {
+ worker.onmessage = (message: MessageEvent) => {
+ const workerOutput: SolcWorkerOutput = message.data
+ if (workerOutput.error) {
+ reject(workerOutput.error)
+ } else {
+ resolve(workerOutput.report!)
+ }
+ worker.terminate()
+ }
+ worker.postMessage({ version, input })
+ })
+ }
+
+ public static countErrors(output: SolcOutput): number {
+ let result = 0
+ for (const e of output.errors ?? []) {
+ if (e.severity == "error") {
+ result += 1
+ }
+ }
+ return result
+ }
+
+ public static fetchMissingFiles(output: SolcOutput): string[] {
+
+ /*
+ {
+ "component": "general",
+ "errorCode": "6275",
+ "formattedMessage": "ParserError: Source \"IHederaTokenService.sol\" not found: File not found: IHederaTokenService.sol\n --> HederaTokenService.sol:6:1:\n |\n6 | import \"./IHederaTokenService.sol\";\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n",
+ "message": "Source \"IHederaTokenService.sol\" not found: File not found: IHederaTokenService.sol",
+ "severity": "error",
+ "sourceLocation": {
+ "end": 177,
+ "file": "HederaTokenService.sol",
+ "start": 142
+ },
+ "type": "ParserError"
+ }
+
+ */
+
+ const result: string[] = []
+ if (output.errors) {
+ const re = /.*: File not found: (.*)/i
+ for (const e of output.errors) {
+ const matches = re.exec(e.message)
+ const fileName = matches && matches.length == 2 ? matches[1] : null
+ if (fileName !== null) {
+ result.push(fileName)
+ }
+ }
+ }
+ return result
+ }
+
+ public static fetchCompilationTarget(metadata: SolcMetadata): string|null {
+ let result: string|null
+ const keys = Object.keys(metadata.settings.compilationTarget)
+ if (keys.length >= 1 && typeof metadata.settings.compilationTarget[keys[0]] == "string") {
+ result = metadata.settings.compilationTarget[keys[0]]
+ } else {
+ result = null
+ }
+ return result
+ }
+
public static fetchIPFSHash(sourceFileName: string, metadata: SolcMetadata): string|null {
let result: string|null = null
if (sourceFileName in metadata.sources) {
@@ -60,4 +133,161 @@ export class SolcUtils {
return result
}
+ public static castSolcMetadata(content: unknown): SolcMetadata|null {
+ let result: SolcMetadata|null
+ /*
+ // https://docs.soliditylang.org/en/latest/metadata.html#contract-metadata
+
+ {
+ "compiler": {
+ "version": "0.8.17+commit.8df45f5f"
+ },
+ "language": "Solidity",
+ "output": {
+ },
+ "settings": {
+ },
+ "sources": {
+ },
+ "version": 1
+ }
+ */
+
+ if (typeof content === "object" && content !== null) {
+ const ok1 = "compiler" in content && typeof content.compiler == "object"
+ const ok2 = "language" in content && content.language == "Solidity"
+ const ok3 = "output" in content && typeof content.output == "object"
+ const ok4 = "settings" in content && typeof content.settings == "object"
+ const ok5 = "sources" in content && typeof content.sources == "object"
+ const ok6 = "version" in content && content.version == "1"
+ result = ok1 && ok2 && ok3 && ok4 && ok5 && ok6 ? content as SolcMetadata : null
+ } else {
+ result = null
+ }
+ return result
+ }
+
+ public static parseSolcMetadata(content: string): SolcMetadata|null {
+ let result: SolcMetadata|null
+ try {
+ const json = JSON.parse(content)
+ result = this.castSolcMetadata(json)
+ } catch {
+ result = null
+ }
+ return result
+ }
+
+ public static castSolcInput(content: unknown): SolcInput|null {
+ let result: SolcInput|null
+ /*
+ // https://docs.soliditylang.org/en/latest/metadata.html#contract-metadata
+
+ {
+ "language": "Solidity",
+ "sources": {
+ },
+ }
+
+ Note: it's like SolcMetadata but without "compiler" nor "version"
+ */
+
+ if (typeof content === "object" && content !== null) {
+ const ko1 = "compiler" in content
+ const ko2 = "version" in content
+ const ok1 = "language" in content && content.language == "Solidity"
+ const ok2 = "sources" in content && typeof content.sources == "object"
+ result = !ko1 && !ko2 && ok1 && ok2 ? content as SolcInput : null
+ } else {
+ result = null
+ }
+ return result
+ }
+
+ public static parseSolcInput(content: string): SolcInput|null {
+ let result: SolcInput|null
+ try {
+ const json = JSON.parse(content)
+ result = this.castSolcInput(json)
+ } catch {
+ result = null
+ }
+ return result
+ }
+
+
+ public static findMatchingContract(deployedBytecode: string, output: SolcOutput): ContractRecord|null {
+ let result: ContractRecord|null = null
+
+ const contracts = output.contracts ?? {}
+ for (const sourceFileName of Object.keys(contracts)) {
+ const contractDescriptions = contracts[sourceFileName]
+ for (const contractName of Object.keys(contractDescriptions)) {
+ const description = contractDescriptions[contractName]
+ const compiledBytecode = description.evm?.deployedBytecode?.object ?? null
+ if (compiledBytecode !== null && compiledBytecode != "") {
+ const comparison = SolcUtils.compareBytecode(deployedBytecode, compiledBytecode)
+ if (comparison !== BytecodeComparison.mismatch) {
+ result = { contractName, sourceFileName, description }
+ break
+ }
+ }
+ }
+ if (result != null) break
+ }
+
+ return result
+ }
+
+ public static compareBytecode(bytecode1: string, bytecode2: string): BytecodeComparison {
+ bytecode1 = bytecode1.startsWith("0x") ? bytecode1.slice(2) : bytecode1
+ bytecode2 = bytecode2.startsWith("0x") ? bytecode2.slice(2) : bytecode2
+
+ // Last bytes of each bytecode represents metadata hash
+ // https://docs.soliditylang.org/en/v0.4.25/metadata.html#encoding-of-the-metadata-hash-in-the-bytecode
+ const components1 = splitAuxdata(bytecode1)
+ const components2 = splitAuxdata(bytecode2)
+ const bytecode1NoHash = components1.length >= 1 ? components1[0] : bytecode1
+ const bytecode2NoHash = components2.length >= 1 ? components2[0] : bytecode2
+
+ let result: BytecodeComparison
+ if (bytecode1 === bytecode2) {
+ result = BytecodeComparison.fullMatch
+ } else if (bytecode1NoHash === bytecode2NoHash) {
+ result = BytecodeComparison.partialMatch
+ } else {
+ result = BytecodeComparison.mismatch
+ }
+
+ return result
+ }
+
}
+
+
+export interface SolcWorkerInput {
+ version: string
+ input: SolcInput
+}
+
+export interface SolcWorkerOutput {
+ report?: SolcReport
+ error?: unknown
+}
+
+export interface SolcReport {
+ output: SolcOutput
+ resolution: Record // importPath -> dropPath
+}
+
+export enum BytecodeComparison {
+ fullMatch = "fullMatch",
+ partialMatch = "partialMatch",
+ mismatch = "mismatch"
+}
+
+export interface ContractRecord {
+ contractName: string
+ sourceFileName: string
+ description: ContractDescription
+}
\ No newline at end of file
diff --git a/src/utils/solc/SolcWorker.ts b/src/utils/solc/SolcWorker.ts
new file mode 100644
index 000000000..96662a7f2
--- /dev/null
+++ b/src/utils/solc/SolcWorker.ts
@@ -0,0 +1,193 @@
+///
+
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {SolcReport, SolcWorkerInput, SolcWorkerOutput} from "@/utils/solc/SolcUtils";
+import {SolcInput} from "@/utils/solc/SolcInput";
+
+//
+// Prefixing with self is very important.
+// In vitest context, self.onmessage works but onmessage does not.
+//
+
+self.onmessage = (event: MessageEvent) => {
+ handleMessage(event)
+ .then((report: SolcReport) => {
+ const response: SolcWorkerOutput = { report: report }
+ self.postMessage(response)
+ })
+ .catch((reason: unknown) => {
+ const response: SolcWorkerOutput = { error: reason }
+ self.postMessage(response)
+ })
+}
+
+async function handleMessage(event: MessageEvent): Promise {
+ const workerInput = event.data as SolcWorkerInput
+ const solcInput = workerInput.input
+ const solc = await makeSolc(workerInput.version)
+ const resolution: Record = {}
+ const importCallback = (path: string) => {
+ const result = {} as { contents?: string, error: unknown }
+ const resolvedPath = resolvePath(path, solcInput)
+ if (resolvedPath !== null) {
+ result.contents = solcInput.sources[resolvedPath].content
+ resolution[path] = resolvedPath
+ } else {
+ result.error = "File not found: " + path
+ }
+ return result
+ }
+ const options = { import: importCallback }
+ const solcOutput = JSON.parse((solc as any).compile(JSON.stringify(workerInput.input), options))
+ return { output: solcOutput, resolution: resolution}
+}
+
+async function makeSolc(version: string): Promise {
+ let result: unknown
+
+ const useImportScripts = "importScripts" in self
+ // true => inside browser
+ // false => inside vitest context
+
+ if (useImportScripts) {
+ // 1) Ideal world:
+ // - just import solc
+ // - worker type can be "classic" or "module"
+ //
+ // Build: OK
+ //
+ // Run: KO
+ // - TypeError: solJson.cwrap is not a function :(
+ // - import statement crashes
+ //
+
+ // result = await import("solc")
+
+ // 2) importScripts() + import() + wrapper() + classic worker
+ // 2.1) importScripts("https://binaries.soliditylang.org/bin/soljson-v0.8.17+commit.8df45f5f.js"
+ // 2.2) await import("solc/wrapper")
+ // 2.3) wrapper(Module)
+ //
+ // Build: OK
+ //
+ // Run: KO
+ // - TypeError: wrapper is not a function
+ // - 2.2 returns an unusable module
+
+ // const compilerURL = "https://binaries.soliditylang.org/bin/soljson-" + version + ".js"
+ // self.importScripts(compilerURL)
+ // const wrapper = (await import("solc/wrapper")).wrapper
+ // result = wrapper((self as any).Module)
+
+ // 2) importScripts() + importScripts() + wrapper() + classic worker
+ // 2.1) importScripts("https://binaries.soliditylang.org/bin/soljson-v0.8.17+commit.8df45f5f.js"
+ // 2.2) importScripts("solc/wrapper")
+ // 2.3) wrapper(Module)
+ //
+ // Build: OK
+ //
+ // Run: KO
+ // - DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://localhost:5173/src/utils/solc/solc/wrapper'
+ // - 2.2 breaks
+
+ // const compilerURL = "https://binaries.soliditylang.org/bin/soljson-" + version + ".js"
+ // self.importScripts(compilerURL)
+ // self.importScripts("solc/wrapper")
+ // result = (self as any).wrapper((self as any).Module)
+
+ // 4) import() + import() + wrapper() + module worker
+ // 4.1) await import("https://binaries.soliditylang.org/bin/soljson-v0.8.17+commit.8df45f5f.js"
+ // 4.2) await import("solc/wrapper")
+ // 4.3) wrapper(Module)
+ //
+ // Build: OK
+ // Run: KO
+ // - 4.1 returns undefined
+ // - 4.2 returns an unusable module
+
+ // const compilerURL = "https://binaries.soliditylang.org/bin/soljson-" + version + ".js"
+ // const soljson = (await import(compilerURL)).Module
+ // const wrapper = (await import("solc/wrapper")).wrapper
+ // result = wrapper(soljson)
+
+ const compilerURL = "https://binaries.soliditylang.org/bin/soljson-" + version + ".js"
+ self.importScripts(compilerURL)
+ const wrapper = (await import("solc/wrapper")).default
+ result = wrapper((self as any).Module)
+
+ } else {
+ const solc = await import("solc")
+ result = new Promise((resolve, reject) => {
+ solc.loadRemoteVersion(version, function(err: unknown, solcSnapshot: typeof solc) {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(solcSnapshot)
+ }
+ })
+ })
+ }
+ return result
+}
+
+function resolvePath(path: string, input: SolcInput): string|null {
+ let result: string|null
+ if (path in input.sources) {
+ result = path
+ } else {
+ result = null
+ const targets = Object.keys(input.sources)
+ for (const t of targets) {
+ if (pathEndsWith(t, path)) {
+ result = t
+ break
+ }
+ }
+ if (result == null) {
+ const i = path.lastIndexOf("/")
+ if (i != -1) {
+ const fileName = path.substring(i+1)
+ for (const t of targets) {
+ if (pathEndsWith(t, fileName)) {
+ result = t
+ break
+ }
+ }
+ }
+ }
+ }
+ return result
+}
+
+function pathEndsWith(path: string, suffix: string): boolean {
+ let result: boolean
+ if (path == suffix) {
+ result = true
+ } else if (path.length >= suffix.length + 1) {
+ const ss1 = "/" + suffix
+ const ss2 = path.substring(path.length - ss1.length)
+ result = ss1 == ss2
+ } else {
+ result = false
+ }
+ return result
+}
diff --git a/src/utils/solc/solc.d.ts b/src/utils/solc/solc.d.ts
new file mode 100644
index 000000000..a7e10890a
--- /dev/null
+++ b/src/utils/solc/solc.d.ts
@@ -0,0 +1,29 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+declare module "solc" {
+ export function loadRemoteVersion(version: string, callback: (error: unknown, snapshot: Solc) => void): void
+ export function compile(solcInput: string): string
+}
+
+declare module "solc/wrapper" {
+ function wrapper(solcJson: unknown): unknown
+ export default wrapper
+}
diff --git a/src/utils/sourcify/SourcifyUtils.ts b/src/utils/sourcify/SourcifyUtils.ts
new file mode 100644
index 000000000..71283ac21
--- /dev/null
+++ b/src/utils/sourcify/SourcifyUtils.ts
@@ -0,0 +1,123 @@
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {SolcInput} from "@/utils/solc/SolcInput";
+import {routeManager} from "@/router";
+import {ContractByIdCache} from "@/utils/cache/ContractByIdCache";
+import axios, {AxiosResponse} from "axios";
+import {SolcMetadata} from "@/utils/solc/SolcMetadata";
+import {SolcUtils} from "@/utils/solc/SolcUtils";
+
+export class SourcifyUtils {
+
+ public static async verifyWithSolcInput(contractId: string,
+ contractName: string,
+ compilerVersion: string,
+ solcInput: SolcInput): Promise {
+ let result: SourcifyVerifyResponse|null
+
+ const contractResponse = await ContractByIdCache.instance.lookup(contractId)
+ const address = contractResponse?.evm_address ?? null
+ const sourcifySetup = routeManager.currentNetworkEntry.value.sourcifySetup
+ if (address !== null && sourcifySetup !== null) {
+ const requestBody: SourcifyVerifyBody = {
+ address: address,
+ chain: sourcifySetup.chainID.toString(),
+ files: {
+ "SolcJsonInput.json": JSON.stringify(solcInput)
+ },
+ compilerVersion: compilerVersion,
+ contractName: contractName
+ }
+ const url = sourcifySetup.serverURL + "verify/solc-json"
+ const sourcifyResponse = await axios.post(url, requestBody)
+ result = sourcifyResponse.data
+ } else {
+ result = null
+ }
+
+ return Promise.resolve(result)
+ }
+
+ public static async verify(contractId: string, metadata: SolcMetadata, inputFiles: Map): Promise {
+ let result: SourcifyVerifyResponse|null
+
+ const contractResponse = await ContractByIdCache.instance.lookup(contractId)
+ const address = contractResponse?.evm_address ?? null
+ const sourcifySetup = routeManager.currentNetworkEntry.value.sourcifySetup
+ if (address !== null && sourcifySetup !== null) {
+ const requestBody: SourcifyVerifyBody = {
+ address: address,
+ chain: sourcifySetup.chainID.toString(),
+ files: {
+ "metadata.json": JSON.stringify(metadata)
+ },
+ contractName: SolcUtils.fetchCompilationTarget(metadata) ?? undefined
+ }
+ for (const [fileName, content] of inputFiles.entries()) {
+ requestBody.files[fileName] = content
+ }
+ const url = sourcifySetup.serverURL + "verify"
+ const sourcifyResponse = await axios.post(url, requestBody)
+ result = sourcifyResponse.data
+ } else {
+ result = null
+ }
+
+ return Promise.resolve(result)
+ }
+
+ public static fetchVerifyError(reason: unknown): string|null {
+ let result: string|null
+
+ if (axios.isAxiosError(reason)) {
+ const response = reason.response as AxiosResponse|undefined
+ result = response?.data.error ?? null
+ } else if ((reason as any).message) {
+ result = (reason as any).message
+ } else {
+ result = null
+ }
+ return result
+ }
+
+ public static fetchVerifyStatus(response: SourcifyVerifyResponse): string|null {
+ return response.result && response.result.length >= 1 ? response.result[0].status : null
+ }
+}
+
+
+export interface SourcifyVerifyBody {
+ address: string
+ chain: string
+ files: Record // filename x content
+ compilerVersion?: string
+ contractName?: string
+}
+
+export interface SourcifyVerifyResponse {
+ error?: string,
+ result?: {
+ address: string,
+ chainId: string,
+ status: string,
+ library: Record
+ }[]
+}
diff --git a/tests/unit/contract/ContractDetails.spec.ts b/tests/unit/contract/ContractDetails.spec.ts
index ab66c9d15..329f85b8e 100644
--- a/tests/unit/contract/ContractDetails.spec.ts
+++ b/tests/unit/contract/ContractDetails.spec.ts
@@ -104,7 +104,7 @@ describe("ContractDetails.vue", () => {
expect(wrapper.get("#evmAddress").text()).toBe("EVM Address:0x00000000000000000000000000000000000b70cfCopy")
expect(wrapper.get("#code").text()).toBe("Runtime Bytecode")
expect(wrapper.get("#solcVersion").text()).toBe("Compiler Version0.8.4")
- expect(wrapper.get("#ipfsHash").text()).toBe("IPFS HashQmap1zNn5JRVVoLFDAKbah7jZyVJAvjqq7f8oUExesSiWT")
+ expect(wrapper.find("#ipfsHash").exists()).toBe(false)
expect(wrapper.find("#swarmHash").exists()).toBe(false)
expect(wrapper.findComponent(ContractResultTable).exists()).toBe(true)
@@ -418,7 +418,7 @@ describe("ContractDetails.vue", () => {
// console.log(wrapper.text())
expect(wrapper.text()).toMatch(RegExp("^Contract Contract ID:" + contract.contract_id))
- expect(wrapper.get("#swarmHashValue").text()).toBe("0x25b12311dff4c2d38251fa91e465b5df31fca9f6c32e034ba551935d652b757a")
+ expect(wrapper.find("#swarmHashValue").exists()).toBe(false)
expect(wrapper.find("#ipfsHash").exists()).toBe(false)
wrapper.unmount()
@@ -427,6 +427,8 @@ describe("ContractDetails.vue", () => {
it("Should display contract verification link and properties", async () => {
+ process.env = Object.assign(process.env, { VITE_APP_ENABLE_VERIFICATION_UI_PHASE2: false });
+
await router.push("/") // To avoid "missing required param 'network'" error
const mock = new MockAdapter(axios);
@@ -453,10 +455,8 @@ describe("ContractDetails.vue", () => {
expect(wrapper.text()).toMatch(RegExp("^Contract Contract ID:" + contractId))
const cards = wrapper.findAllComponents(DashboardCard)
- expect(cards[1].text()).toMatch(RegExp("^Contract Details"))
- expect(cards[1].get('a').text()).toBe("Verify Contract (beta)")
- expect(cards[1].get("#verificationStatusValue").text()).toBe("Not yet verified")
- expect(cards[1].get("#contractNameValue").text()).toBe("None")
+ expect(cards[1].text()).toMatch(RegExp("^Contract Bytecode"))
+ expect(cards[1].get('a').text()).toBe("Verify contract (beta)")
wrapper.unmount()
await flushPromises()
diff --git a/tests/unit/globalSetup.js b/tests/unit/globalSetup.js
index b384af22c..e1e9d9e29 100644
--- a/tests/unit/globalSetup.js
+++ b/tests/unit/globalSetup.js
@@ -1,8 +1,10 @@
import { beforeEach, vi } from 'vitest'
import {CacheUtils} from "@/utils/cache/CacheUtils";
+import {SolcIndexCache} from "@/utils/cache/SolcIndexCache";
beforeEach(() => {
CacheUtils.clearAll()
+ SolcIndexCache.instance.clear()
})
Object.defineProperty(window, 'matchMedia', {
diff --git a/tests/unit/staking/StakingDialog.spec.ts b/tests/unit/staking/StakingDialog.spec.ts
index 9e18ab9f3..056c3d027 100644
--- a/tests/unit/staking/StakingDialog.spec.ts
+++ b/tests/unit/staking/StakingDialog.spec.ts
@@ -171,6 +171,7 @@ describe("StakingDialog.vue", () => {
await nextTick()
await confirmChangeStaking("Change Staking for account 0.0.730632Do you want to stake to account 0.0.7-bmurp ?FillerCANCELCONFIRM")
+ mock.restore()
wrapper.unmount()
await flushPromises()
})
@@ -279,6 +280,7 @@ describe("StakingDialog.vue", () => {
await flushPromises()
expect(feedbackMessage.text()).toBe("This account does not exist")
+ mock.restore()
wrapper.unmount()
await flushPromises()
})
diff --git a/tests/unit/utils/ContractAnalyzer.spec.ts b/tests/unit/utils/ContractAnalyzer.spec.ts
index 9343762bf..3a2919463 100644
--- a/tests/unit/utils/ContractAnalyzer.spec.ts
+++ b/tests/unit/utils/ContractAnalyzer.spec.ts
@@ -20,12 +20,12 @@
*
*/
-import {describe, test, expect} from 'vitest'
+import {describe, expect, test} from 'vitest'
import {Ref, ref} from "vue";
import {flushPromises} from "@vue/test-utils";
import MockAdapter from "axios-mock-adapter";
import axios from "axios";
-import {ContractAnalyzer, MetadataOrigin} from "@/utils/analyzer/ContractAnalyzer";
+import {ContractAnalyzer} from "@/utils/analyzer/ContractAnalyzer";
import {SAMPLE_CONTRACT} from "../Mocks";
import {SourcifyResponse} from "@/utils/cache/SourcifyCache";
import {routeManager} from "@/router";
@@ -42,7 +42,6 @@ describe("ContractAnalyzer.spec.ts", () => {
const contractId: Ref = ref(null)
const contractAnalyzer = new ContractAnalyzer(contractId)
expect(contractAnalyzer.contractId.value).toBeNull()
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
@@ -54,7 +53,6 @@ describe("ContractAnalyzer.spec.ts", () => {
contractAnalyzer.mount()
await flushPromises()
expect(contractAnalyzer.contractId.value).toBeNull()
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
@@ -66,7 +64,6 @@ describe("ContractAnalyzer.spec.ts", () => {
contractId.value = SAMPLE_CONTRACT.contract_id
await flushPromises()
expect(contractAnalyzer.contractId.value).toBe(SAMPLE_CONTRACT.contract_id)
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
@@ -78,7 +75,6 @@ describe("ContractAnalyzer.spec.ts", () => {
contractAnalyzer.unmount()
await flushPromises()
expect(contractAnalyzer.contractId.value).toBe(SAMPLE_CONTRACT.contract_id)
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
@@ -97,14 +93,13 @@ describe("ContractAnalyzer.spec.ts", () => {
const networkEntry = routeManager.currentNetworkEntry.value
const requestURL = networkEntry.sourcifySetup?.makeRequestURL(SAMPLE_CONTRACT.evm_address)
- const contractURL = networkEntry.sourcifySetup?.makeContractLookupURL(SAMPLE_CONTRACT.evm_address)
+ const contractURL = networkEntry.sourcifySetup?.makeContractSourceURL(SAMPLE_CONTRACT.evm_address, true)
mock.onGet(requestURL).reply(200, SAMPLE_SOURCIFY_RESPONSE)
// 1) new
const contractId: Ref = ref(null)
const contractAnalyzer = new ContractAnalyzer(contractId)
expect(contractAnalyzer.contractId.value).toBeNull()
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
@@ -116,7 +111,6 @@ describe("ContractAnalyzer.spec.ts", () => {
contractAnalyzer.mount()
await flushPromises()
expect(contractAnalyzer.contractId.value).toBeNull()
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
@@ -128,7 +122,6 @@ describe("ContractAnalyzer.spec.ts", () => {
contractId.value = SAMPLE_CONTRACT.contract_id
await flushPromises()
expect(contractAnalyzer.contractId.value).toBe(SAMPLE_CONTRACT.contract_id)
- expect(contractAnalyzer.metadataOrigin.value).toBe(MetadataOrigin.Sourcify)
expect(contractAnalyzer.sourceFileName.value).toBe("HTSv2.sol")
expect(contractAnalyzer.contractName.value).toBe("HTS")
expect(contractAnalyzer.interface.value).not.toBeNull()
@@ -143,7 +136,6 @@ describe("ContractAnalyzer.spec.ts", () => {
expect(contractAnalyzer.sourceFileName.value).toBeNull()
expect(contractAnalyzer.contractName.value).toBeNull()
expect(contractAnalyzer.interface.value).toBeNull()
- expect(contractAnalyzer.metadataOrigin.value).toBeNull()
expect(contractAnalyzer.byteCode.value).toBeNull()
expect(contractAnalyzer.fullMatch.value).toBeNull()
expect(contractAnalyzer.sourcifyURL.value).toBeNull()
diff --git a/tests/unit/utils/analyzer/ContractSourceAudit.spec.ts b/tests/unit/utils/analyzer/ContractSourceAudit.spec.ts
new file mode 100644
index 000000000..2223c676f
--- /dev/null
+++ b/tests/unit/utils/analyzer/ContractSourceAudit.spec.ts
@@ -0,0 +1,101 @@
+// noinspection DuplicatedCode
+
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import {describe, expect, test} from 'vitest'
+import {readFileSync} from "fs";
+import {SolcMetadata} from "../../../../src/utils/solc/SolcMetadata";
+import {
+ ContractAuditItemStatus,
+ ContractAuditStatus,
+ ContractSourceAudit
+} from "../../../../src/utils/analyzer/ContractSourceAudit";
+
+describe("ContractSourceAudit.spec.ts", () => {
+
+ test("test1", async () => {
+
+ const files = new Map( [
+ ["metadata.json", jsonContentOfFile("HTS_meta.json") as SolcMetadata],
+ ["HederaResponseCodes.sol", contentOfFile("HederaResponseCodes.sol")],
+ ["HederaTokenService.sol", contentOfFile("HederaTokenService.sol")],
+ ["HTSv2.sol", contentOfFile("HTSv2.sol")],
+ ["IHederaTokenService.sol", contentOfFile("IHederaTokenService.sol")],
+ ["Unused.sol", contentOfFile("Unused.sol")],
+ ])
+
+ const solcVersion = "0.8.17"
+
+ const deployedByteCode = contentOfFile("HTS_runtime_bytecode.bin")
+
+ const audit = await ContractSourceAudit.build(files, solcVersion, deployedByteCode)
+ expect(audit.status).toBe(ContractAuditStatus.Resolved)
+ expect(audit.items.length).toBe(6)
+ expect(audit.longCompilerVersion).toBe("0.8.17+commit.8df45f5f")
+ expect(audit.resolvedContractName).toBe("HTS")
+ expect(audit.resolvedMetadata).toStrictEqual(jsonContentOfFile("HTS_meta.json"))
+
+ const i0 = audit.items[0]
+ expect(i0.path).toBe("metadata.json")
+ expect(i0.content).toStrictEqual(jsonContentOfFile("HTS_meta.json"))
+ expect(i0.status).toBe(ContractAuditItemStatus.OK)
+ expect(i0.target).toBe(true)
+
+ const i1 = audit.items[1]
+ expect(i1.path).toBe("HederaResponseCodes.sol")
+ expect(i1.content).toStrictEqual(contentOfFile("HederaResponseCodes.sol"))
+ expect(i1.status).toBe(ContractAuditItemStatus.OK)
+ expect(i1.target).toBe(false)
+
+ const i2 = audit.items[2]
+ expect(i2.path).toBe("HederaTokenService.sol")
+ expect(i2.content).toStrictEqual(contentOfFile("HederaTokenService.sol"))
+ expect(i2.status).toBe(ContractAuditItemStatus.OK)
+ expect(i2.target).toBe(false)
+
+ const i3 = audit.items[3]
+ expect(i3.path).toBe("HTSv2.sol")
+ expect(i3.content).toStrictEqual(contentOfFile("HTSv2.sol"))
+ expect(i3.status).toBe(ContractAuditItemStatus.OK)
+ expect(i3.target).toBe(true)
+
+ const i4 = audit.items[4]
+ expect(i4.path).toBe("IHederaTokenService.sol")
+ expect(i4.content).toStrictEqual(contentOfFile("IHederaTokenService.sol"))
+ expect(i4.status).toBe(ContractAuditItemStatus.OK)
+ expect(i4.target).toBe(false)
+
+ const i5 = audit.items[5]
+ expect(i5.path).toBe("Unused.sol")
+ expect(i5.content).toStrictEqual(contentOfFile("Unused.sol"))
+ expect(i5.status).toBe(ContractAuditItemStatus.Unused)
+ expect(i5.target).toBe(false)
+
+ })
+})
+
+function contentOfFile(fileName: string): string {
+ return readFileSync(__dirname + "/../solc/hts/" + fileName).toString()
+}
+
+function jsonContentOfFile(fileName: string): unknown {
+ return JSON.parse(contentOfFile(fileName))
+}
diff --git a/tests/unit/utils/solc/SolcLauncher.spec.ts b/tests/unit/utils/solc/SolcLauncher.spec.ts
new file mode 100644
index 000000000..2bd4a3e61
--- /dev/null
+++ b/tests/unit/utils/solc/SolcLauncher.spec.ts
@@ -0,0 +1,483 @@
+// noinspection DuplicatedCode
+
+/*-
+ *
+ * Hedera Mirror Node Explorer
+ *
+ * Copyright (C) 2021 - 2023 Hedera Hashgraph, LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+import {describe, expect, test} from 'vitest'
+import {readFileSync} from "fs";
+import {SolcUtils} from "@/utils/solc/SolcUtils";
+
+describe("SolcLauncher", () => {
+
+ test("HelloWorld", async () => {
+
+ const input = {
+ "language":"Solidity",
+ "sources":{
+ "HelloWorld.sol":{
+ "content": contentOfFile("hello_world/HelloWorld.sol")
+ }
+ }
+ }
+
+ const output = {
+ "errors": [
+ {
+ "component": "general",
+ "errorCode": "1878",
+ "formattedMessage": "Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing \"SPDX-License-Identifier: \" to each source file. Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. Please see https://spdx.org for more information.\n--> HelloWorld.sol\n\n",
+ "message": "SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing \"SPDX-License-Identifier: \" to each source file. Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. Please see https://spdx.org for more information.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": -1,
+ "file": "HelloWorld.sol",
+ "start": -1
+ },
+ "type": "Warning"
+ }
+ ],
+ "sources": {
+ "HelloWorld.sol": {
+ "id": 0
+ }
+ }
+ }
+
+ const report = await SolcUtils.runAsWorker("v0.8.17+commit.8df45f5f", input)
+ expect(report.output).toStrictEqual(output)
+
+ }, 20000)
+
+ test("HTS", async () => {
+
+ const input = {
+ "language":"Solidity",
+ "sources":{
+ "HTSv2.sol": {
+ "content": contentOfFile("hts/HTSv2.sol")
+ },
+ "HederaResponseCodes.sol": {
+ "content": contentOfFile("hts/HederaResponseCodes.sol")
+ },
+ "HederaTokenService.sol": {
+ "content": contentOfFile("hts/HederaTokenService.sol")
+ },
+ "IHederaTokenService.sol": {
+ "content": contentOfFile("hts/IHederaTokenService.sol")
+ }
+ }
+ }
+
+ const output = {
+ "sources":{
+ "HTSv2.sol":{"id":0},
+ "HederaResponseCodes.sol":{"id":1},
+ "HederaTokenService.sol":{"id":2},
+ "IHederaTokenService.sol":{"id":3}
+ }
+ }
+
+ const report = await SolcUtils.runAsWorker("v0.8.17+commit.8df45f5f", input)
+ expect(report.output).toStrictEqual(output)
+ }, 20000)
+
+ test("HTS (with missing file)", async () => {
+
+ const input = {
+ "language":"Solidity",
+ "sources":{
+ "HTSv2.sol": {
+ "content": contentOfFile("hts/HTSv2.sol")
+ }
+ }
+ }
+
+ const output = {
+ "errors": [
+ {
+ "component": "general",
+ "errorCode": "6275",
+ "formattedMessage": "ParserError: Source \"HederaTokenService.sol\" not found: File not found: HederaTokenService.sol\n --> HTSv2.sol:4:1:\n |\n4 | import \"./HederaTokenService.sol\";\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n",
+ "message": "Source \"HederaTokenService.sol\" not found: File not found: HederaTokenService.sol",
+ "severity": "error",
+ "sourceLocation": {
+ "end": 99,
+ "file": "HTSv2.sol",
+ "start": 65
+ },
+ "type": "ParserError"
+ },
+ {
+ "component": "general",
+ "errorCode": "6275",
+ "formattedMessage": "ParserError: Source \"HederaResponseCodes.sol\" not found: File not found: HederaResponseCodes.sol\n --> HTSv2.sol:5:1:\n |\n5 | import \"./HederaResponseCodes.sol\";\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n",
+ "message": "Source \"HederaResponseCodes.sol\" not found: File not found: HederaResponseCodes.sol",
+ "severity": "error",
+ "sourceLocation": {
+ "end": 135,
+ "file": "HTSv2.sol",
+ "start": 100
+ },
+ "type": "ParserError"
+ }
+ ],
+ "sources": {}
+ }
+
+ const report = await SolcUtils.runAsWorker("v0.8.17+commit.8df45f5f", input)
+ expect(report.output).toStrictEqual(output)
+ const missingFiles = SolcUtils.fetchMissingFiles(report.output)
+ expect(missingFiles).toStrictEqual(["HederaTokenService.sol", "HederaResponseCodes.sol"])
+ }, 20000)
+
+ test("HTS (with unused file)", async () => {
+
+ const input = {
+ "language":"Solidity",
+ "sources":{
+ "HTSv2.sol": {
+ "content": contentOfFile("hts/HTSv2.sol")
+ },
+ "HederaResponseCodes.sol": {
+ "content": contentOfFile("hts/HederaResponseCodes.sol")
+ },
+ "HederaTokenService.sol": {
+ "content": contentOfFile("hts/HederaTokenService.sol")
+ },
+ "IHederaTokenService.sol": {
+ "content": contentOfFile("hts/IHederaTokenService.sol")
+ },
+ "Unused.sol":{
+ "content": contentOfFile("hts/Unused.sol")
+ }
+ }
+ }
+
+ const output = {
+ "sources": {
+ "HTSv2.sol": {
+ "id": 0
+ },
+ "HederaResponseCodes.sol": {
+ "id": 1
+ },
+ "HederaTokenService.sol": {
+ "id": 2
+ },
+ "IHederaTokenService.sol": {
+ "id": 3
+ },
+ "Unused.sol": {
+ "id": 4
+ }
+ }
+ }
+
+
+ const report = await SolcUtils.runAsWorker("v0.8.17+commit.8df45f5f", input)
+ expect(report.output).toStrictEqual(output)
+ }, 20000)
+
+ test("HTS (with obsolete compiler)", async () => {
+
+ const input = {
+ "language":"Solidity",
+ "sources":{
+ "HTSv2.sol": {
+ "content": contentOfFile("hts/HTSv2.sol")
+ },
+ "HederaResponseCodes.sol": {
+ "content": contentOfFile("hts/HederaResponseCodes.sol")
+ },
+ "HederaTokenService.sol": {
+ "content": contentOfFile("hts/HederaTokenService.sol")
+ },
+ "IHederaTokenService.sol": {
+ "content": contentOfFile("hts/IHederaTokenService.sol")
+ },
+ "Unused.sol":{
+ "content": contentOfFile("hts/Unused.sol")
+ }
+ }
+ }
+
+ const output = {
+ "errors": [
+ {
+ "component": "general",
+ "errorCode": "5333",
+ "formattedMessage": "HTSv2.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version\npragma solidity ^0.8.17;\n^----------------------^\n",
+ "message": "Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version",
+ "severity": "error",
+ "sourceLocation": {
+ "end": 63,
+ "file": "HTSv2.sol",
+ "start": 39
+ },
+ "type": "ParserError"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:175:21: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n HederaToken token;\n ^---^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 8391,
+ "file": "IHederaTokenService.sol",
+ "start": 8386
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:178:15: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n int64 totalSupply;\n ^---------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 8502,
+ "file": "IHederaTokenService.sol",
+ "start": 8491
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:181:14: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n bool deleted;\n ^-----^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 8583,
+ "file": "IHederaTokenService.sol",
+ "start": 8576
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:184:14: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n bool defaultKycStatus;\n ^--------------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 8721,
+ "file": "IHederaTokenService.sol",
+ "start": 8705
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:187:14: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n bool pauseStatus;\n ^---------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 8815,
+ "file": "IHederaTokenService.sol",
+ "start": 8804
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:190:20: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n FixedFee[] fixedFees;\n ^-------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 8911,
+ "file": "IHederaTokenService.sol",
+ "start": 8902
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:193:25: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n FractionalFee[] fractionalFees;\n ^------------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9022,
+ "file": "IHederaTokenService.sol",
+ "start": 9008
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:196:22: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n RoyaltyFee[] royaltyFees;\n ^---------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9124,
+ "file": "IHederaTokenService.sol",
+ "start": 9113
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:199:16: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n string ledgerId;\n ^------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9191,
+ "file": "IHederaTokenService.sol",
+ "start": 9183
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:205:19: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n TokenInfo tokenInfo;\n ^-------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9357,
+ "file": "IHederaTokenService.sol",
+ "start": 9348
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:208:15: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n int32 decimals;\n ^------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9447,
+ "file": "IHederaTokenService.sol",
+ "start": 9439
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:214:19: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n TokenInfo tokenInfo;\n ^-------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9620,
+ "file": "IHederaTokenService.sol",
+ "start": 9611
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:217:15: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n int64 serialNumber;\n ^----------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9690,
+ "file": "IHederaTokenService.sol",
+ "start": 9678
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:220:17: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n address ownerId;\n ^-----^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9790,
+ "file": "IHederaTokenService.sol",
+ "start": 9783
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:223:15: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n int64 creationTime;\n ^----------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9880,
+ "file": "IHederaTokenService.sol",
+ "start": 9868
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:226:15: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n bytes metadata;\n ^------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 9948,
+ "file": "IHederaTokenService.sol",
+ "start": 9940
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "2837",
+ "formattedMessage": "IHederaTokenService.sol:229:17: Warning: Only state variables can have a docstring. This will be disallowed in 0.7.0.\n address spenderId;\n ^-------^\n",
+ "message": "Only state variables can have a docstring. This will be disallowed in 0.7.0.",
+ "severity": "warning",
+ "sourceLocation": {
+ "end": 10080,
+ "file": "IHederaTokenService.sol",
+ "start": 10071
+ },
+ "type": "Warning"
+ },
+ {
+ "component": "general",
+ "errorCode": "5333",
+ "formattedMessage": "Unused.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version\npragma solidity ^0.8.17;\n^----------------------^\n",
+ "message": "Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version",
+ "severity": "error",
+ "sourceLocation": {
+ "end": 63,
+ "file": "Unused.sol",
+ "start": 39
+ },
+ "type": "ParserError"
+ }
+ ],
+ "sources": {}
+ }
+
+
+ const report = await SolcUtils.runAsWorker("v0.6.12+commit.27d51765", input)
+ expect(report.output).toStrictEqual(output)
+ }, 20000)
+})
+
+function contentOfFile(fileName: string): string {
+ return readFileSync(__dirname + "/" + fileName).toString()
+}
\ No newline at end of file
diff --git a/tests/unit/utils/solc/hello_world/HelloWorld.sol b/tests/unit/utils/solc/hello_world/HelloWorld.sol
new file mode 100644
index 000000000..742db7a81
--- /dev/null
+++ b/tests/unit/utils/solc/hello_world/HelloWorld.sol
@@ -0,0 +1,16 @@
+pragma solidity ^0.8.17;
+
+contract HelloWorld {
+
+ string public message;
+
+ constructor(string memory initMessage) {
+
+ message = initMessage;
+ }
+
+ function update(string memory newMessage) public {
+ message = newMessage;
+ }
+}
+
diff --git a/tests/unit/utils/solc/hts/HTS_meta.json b/tests/unit/utils/solc/hts/HTS_meta.json
new file mode 100644
index 000000000..3796a459b
--- /dev/null
+++ b/tests/unit/utils/solc/hts/HTS_meta.json
@@ -0,0 +1 @@
+{"compiler":{"version":"0.8.17+commit.8df45f5f"},"language":"Solidity","output":{"abi":[{"inputs":[],"name":"brokenDissociate","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"delegateTransferFrom","outputs":[{"internalType":"int64","name":"responseCode","type":"int64"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"serialNumber","type":"uint256"}],"name":"delegateTransferFromNFT","outputs":[{"internalType":"int64","name":"responseCode","type":"int64"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"tokenAssociate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"tokenDissociate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenId","type":"address"},{"internalType":"address","name":"fromAccountId","type":"address"},{"internalType":"address","name":"toAccountId","type":"address"},{"internalType":"int64","name":"tokenAmount","type":"int64"}],"name":"tokenTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"int64","name":"responseCode","type":"int64"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"serialNumber","type":"uint256"}],"name":"transferFromNFT","outputs":[{"internalType":"int64","name":"responseCode","type":"int64"}],"stateMutability":"nonpayable","type":"function"}],"devdoc":{"kind":"dev","methods":{"delegateTransferFrom(address,address,address,uint256)":{"params":{"amount":"The amount of tokens to transfer from `from` to `to`","from":"The account address of the owner of the token, on the behalf of which to transfer `amount` tokens","to":"The account address of the receiver of the `amount` tokens","token":"The address of the fungible Hedera token to transfer"},"returns":{"responseCode":"The response code for the status of the request. SUCCESS is 22."}},"delegateTransferFromNFT(address,address,address,uint256)":{"params":{"from":"The account address of the owner of `serialNumber` of `token`","serialNumber":"The NFT serial number to transfer","to":"The account address of the receiver of `serialNumber`","token":"The address of the non-fungible Hedera token to transfer"},"returns":{"responseCode":"The response code for the status of the request. SUCCESS is 22."}},"transferFrom(address,address,address,uint256)":{"params":{"amount":"The amount of tokens to transfer from `from` to `to`","from":"The account address of the owner of the token, on the behalf of which to transfer `amount` tokens","to":"The account address of the receiver of the `amount` tokens","token":"The address of the fungible Hedera token to transfer"},"returns":{"responseCode":"The response code for the status of the request. SUCCESS is 22."}},"transferFromNFT(address,address,address,uint256)":{"params":{"from":"The account address of the owner of `serialNumber` of `token`","serialNumber":"The NFT serial number to transfer","to":"The account address of the receiver of `serialNumber`","token":"The address of the non-fungible Hedera token to transfer"},"returns":{"responseCode":"The response code for the status of the request. SUCCESS is 22."}}},"version":1},"userdoc":{"kind":"user","methods":{"delegateTransferFrom(address,address,address,uint256)":{"notice":"Only applicable to fungible tokens"},"delegateTransferFromNFT(address,address,address,uint256)":{"notice":"Transfers `serialNumber` of `token` from `from` to `to` using the allowance mechanism. Only applicable to NFT tokens"},"transferFrom(address,address,address,uint256)":{"notice":"Only applicable to fungible tokens"},"transferFromNFT(address,address,address,uint256)":{"notice":"Transfers `serialNumber` of `token` from `from` to `to` using the allowance mechanism. Only applicable to NFT tokens"}},"version":1}},"settings":{"compilationTarget":{"HTSv2.sol":"HTS"},"evmVersion":"london","libraries":{},"metadata":{"bytecodeHash":"ipfs"},"optimizer":{"enabled":false,"runs":200},"remappings":[]},"sources":{"HTSv2.sol":{"keccak256":"0xd2e8a58e779fa39eae7fb463637069f25b96bf076d50d234e3c30d3874c6d3a1","license":"Apache-2.0","urls":["bzz-raw://0c73187c03bffbe5dab6f33beb9fdaf50b9e69b526bc56b73e0393b75b965997","dweb:/ipfs/QmWQNaXji5qCgaC6SXbcgbW6RR8zHChqQtT9bB5Sn5m5Bk"]},"HederaResponseCodes.sol":{"keccak256":"0x0361e18efdf43d6b5ac136b6beaa4c943d7fe5e9b8515e5605e3a13b3e3a8177","license":"Apache-2.0","urls":["bzz-raw://d8bc2fcf2c308293f8ba791184080ab67406e973d2e3f1c70976a77f26a41752","dweb:/ipfs/QmQrC4wQ1z7GiC79FLa2rbJDqDNCqkHVf3xLq2stFtpema"]},"HederaTokenService.sol":{"keccak256":"0x49e7beb1242fe0cb86c9a8d9f8203f5129bf67da0202d9a6d6d2befa836bfe3b","license":"Apache-2.0","urls":["bzz-raw://2a913eef60a88889edeb25eafeb60b83e3a1a5d6f1e26a1f8db4177e4124adf5","dweb:/ipfs/Qmck14PhfWDM7vkebqQL9UErQYNENV7FYhyLLQbq8qigXH"]},"IHederaTokenService.sol":{"keccak256":"0x8510798a2ed2d4cfba89eb624fcdda0c69d637c5512c4386628512798c72132b","license":"Apache-2.0","urls":["bzz-raw://4b511edd0e89f39ef5c274ec30ea1d524043c9f4d349394265c69eee745c06b5","dweb:/ipfs/QmNr2VMMLrtfz5bEbwb9gAKcyvj7qRqwacErRFsDuxRUbb"]}},"version":1}
\ No newline at end of file
diff --git a/tests/unit/utils/solc/hts/HTS_runtime_bytecode.bin b/tests/unit/utils/solc/hts/HTS_runtime_bytecode.bin
new file mode 100644
index 000000000..1fd99d691
--- /dev/null
+++ b/tests/unit/utils/solc/hts/HTS_runtime_bytecode.bin
@@ -0,0 +1 @@
+608060405234801561001057600080fd5b50600436106100885760003560e01c80634753b51b1161005b5780634753b51b146101135780637f6314d01461012f5780639b23d3d91461014b578063eac6f3fe1461017b57610088565b806311e1fc071461008d57806315dacbea146100bd578063341fa473146100ed5780633a04033c146100f7575b600080fd5b6100a760048036038101906100a29190610b50565b6101ab565b6040516100b49190610bd3565b60405180910390f35b6100d760048036038101906100d29190610b50565b6102c7565b6040516100e49190610bd3565b60405180910390f35b6100f56103e5565b005b610111600480360381019061010c9190610c1a565b610420565b005b61012d60048036038101906101289190610c81565b61047d565b005b61014960048036038101906101449190610c81565b6104d6565b005b61016560048036038101906101609190610b50565b61052f565b6040516101729190610bd3565b60405180910390f35b61019560048036038101906101909190610b50565b61064d565b6040516101a29190610bd3565b60405180910390f35b600080600061016773ffffffffffffffffffffffffffffffffffffffff16639b23d3d960e01b888888886040516024016101e89493929190610cdf565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040516102529190610d95565b600060405180830381855af49150503d806000811461028d576040519150601f19603f3d011682016040523d82523d6000602084013e610292565b606091505b5091509150816102a35760156102b8565b808060200190518101906102b79190610de5565b5b60030b92505050949350505050565b600080600061016773ffffffffffffffffffffffffffffffffffffffff166315dacbea60e01b888888886040516024016103049493929190610cdf565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505060405161036e9190610d95565b6000604051808303816000865af19150503d80600081146103ab576040519150601f19603f3d011682016040523d82523d6000602084013e6103b0565b606091505b5091509150816103c15760156103d6565b808060200190518101906103d59190610de5565b5b60030b92505050949350505050565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161041790610e6f565b60405180910390fd5b600061042e85858585610769565b9050601660030b8114610476576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161046d90610edb565b60405180910390fd5b5050505050565b60006104898383610887565b9050601660030b81146104d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104c890610f47565b60405180910390fd5b505050565b60006104e2838361099f565b9050601660030b811461052a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161052190610fb3565b60405180910390fd5b505050565b600080600061016773ffffffffffffffffffffffffffffffffffffffff16639b23d3d960e01b8888888860405160240161056c9493929190610cdf565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040516105d69190610d95565b6000604051808303816000865af19150503d8060008114610613576040519150601f19603f3d011682016040523d82523d6000602084013e610618565b606091505b50915091508161062957601561063e565b8080602001905181019061063d9190610de5565b5b60030b92505050949350505050565b600080600061016773ffffffffffffffffffffffffffffffffffffffff166315dacbea60e01b8888888860405160240161068a9493929190610cdf565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040516106f49190610d95565b600060405180830381855af49150503d806000811461072f576040519150601f19603f3d011682016040523d82523d6000602084013e610734565b606091505b50915091508161074557601561075a565b808060200190518101906107599190610de5565b5b60030b92505050949350505050565b600080600061016773ffffffffffffffffffffffffffffffffffffffff1663eca3691760e01b888888886040516024016107a69493929190610fd3565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040516108109190610d95565b6000604051808303816000865af19150503d806000811461084d576040519150601f19603f3d011682016040523d82523d6000602084013e610852565b606091505b509150915081610863576015610878565b808060200190518101906108779190610de5565b5b60030b92505050949350505050565b600080600061016773ffffffffffffffffffffffffffffffffffffffff1663099794e860e01b86866040516024016108c0929190611018565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505060405161092a9190610d95565b6000604051808303816000865af19150503d8060008114610967576040519150601f19603f3d011682016040523d82523d6000602084013e61096c565b606091505b50915091508161097d576015610992565b808060200190518101906109919190610de5565b5b60030b9250505092915050565b600080600061016773ffffffffffffffffffffffffffffffffffffffff166349146bde60e01b86866040516024016109d8929190611018565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050604051610a429190610d95565b6000604051808303816000865af19150503d8060008114610a7f576040519150601f19603f3d011682016040523d82523d6000602084013e610a84565b606091505b509150915081610a95576015610aaa565b80806020019051810190610aa99190610de5565b5b60030b9250505092915050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000610ae782610abc565b9050919050565b610af781610adc565b8114610b0257600080fd5b50565b600081359050610b1481610aee565b92915050565b6000819050919050565b610b2d81610b1a565b8114610b3857600080fd5b50565b600081359050610b4a81610b24565b92915050565b60008060008060808587031215610b6a57610b69610ab7565b5b6000610b7887828801610b05565b9450506020610b8987828801610b05565b9350506040610b9a87828801610b05565b9250506060610bab87828801610b3b565b91505092959194509250565b60008160070b9050919050565b610bcd81610bb7565b82525050565b6000602082019050610be86000830184610bc4565b92915050565b610bf781610bb7565b8114610c0257600080fd5b50565b600081359050610c1481610bee565b92915050565b60008060008060808587031215610c3457610c33610ab7565b5b6000610c4287828801610b05565b9450506020610c5387828801610b05565b9350506040610c6487828801610b05565b9250506060610c7587828801610c05565b91505092959194509250565b60008060408385031215610c9857610c97610ab7565b5b6000610ca685828601610b05565b9250506020610cb785828601610b05565b9150509250929050565b610cca81610adc565b82525050565b610cd981610b1a565b82525050565b6000608082019050610cf46000830187610cc1565b610d016020830186610cc1565b610d0e6040830185610cc1565b610d1b6060830184610cd0565b95945050505050565b600081519050919050565b600081905092915050565b60005b83811015610d58578082015181840152602081019050610d3d565b60008484015250505050565b6000610d6f82610d24565b610d798185610d2f565b9350610d89818560208601610d3a565b80840191505092915050565b6000610da18284610d64565b915081905092915050565b60008160030b9050919050565b610dc281610dac565b8114610dcd57600080fd5b50565b600081519050610ddf81610db9565b92915050565b600060208284031215610dfb57610dfa610ab7565b5b6000610e0984828501610dd0565b91505092915050565b600082825260208201905092915050565b7f5468697320646973736f63696174652069732062726f6b656e00000000000000600082015250565b6000610e59601983610e12565b9150610e6482610e23565b602082019050919050565b60006020820190508181036000830152610e8881610e4c565b9050919050565b7f5472616e73666572204661696c65640000000000000000000000000000000000600082015250565b6000610ec5600f83610e12565b9150610ed082610e8f565b602082019050919050565b60006020820190508181036000830152610ef481610eb8565b9050919050565b7f446973736f6369617465204661696c6564000000000000000000000000000000600082015250565b6000610f31601183610e12565b9150610f3c82610efb565b602082019050919050565b60006020820190508181036000830152610f6081610f24565b9050919050565b7f4173736f6369617465204661696c656400000000000000000000000000000000600082015250565b6000610f9d601083610e12565b9150610fa882610f67565b602082019050919050565b60006020820190508181036000830152610fcc81610f90565b9050919050565b6000608082019050610fe86000830187610cc1565b610ff56020830186610cc1565b6110026040830185610cc1565b61100f6060830184610bc4565b95945050505050565b600060408201905061102d6000830185610cc1565b61103a6020830184610cc1565b939250505056fea264697066735822122044cb0d8cd4389a1498cf6bd7d112216a1538790b483bed3d627b71b7426e795e64736f6c63430008110033
\ No newline at end of file
diff --git a/tests/unit/utils/solc/hts/HTSv2.sol b/tests/unit/utils/solc/hts/HTSv2.sol
new file mode 100644
index 000000000..2a0c014ed
--- /dev/null
+++ b/tests/unit/utils/solc/hts/HTSv2.sol
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity ^0.8.17;
+
+import "./HederaTokenService.sol";
+import "./HederaResponseCodes.sol";
+
+
+contract HTS is HederaTokenService {
+
+ function tokenAssociate(address sender, address tokenAddress) external {
+ int response = HederaTokenService.associateToken(sender, tokenAddress);
+
+ if (response != HederaResponseCodes.SUCCESS) {
+ revert ("Associate Failed");
+ }
+ }
+
+ function tokenTransfer(address tokenId, address fromAccountId , address toAccountId , int64 tokenAmount) external {
+ int response = HederaTokenService.transferToken(tokenId, fromAccountId, toAccountId, tokenAmount);
+
+ if (response != HederaResponseCodes.SUCCESS) {
+ revert ("Transfer Failed");
+ }
+ }
+
+ function tokenDissociate(address sender, address tokenAddress) external {
+ int response = HederaTokenService.dissociateToken(sender, tokenAddress);
+
+ if (response != HederaResponseCodes.SUCCESS) {
+ revert ("Dissociate Failed");
+ }
+ }
+
+ function brokenDissociate() external pure {
+ revert ("This dissociate is broken");
+ }
+}
\ No newline at end of file
diff --git a/tests/unit/utils/solc/hts/HederaResponseCodes.sol b/tests/unit/utils/solc/hts/HederaResponseCodes.sol
new file mode 100644
index 000000000..229dfb6f4
--- /dev/null
+++ b/tests/unit/utils/solc/hts/HederaResponseCodes.sol
@@ -0,0 +1,311 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity >=0.4.9 <0.9.0;
+
+library HederaResponseCodes {
+
+ // response codes
+ int32 internal constant OK = 0; // The transaction passed the precheck validations.
+ int32 internal constant INVALID_TRANSACTION = 1; // For any error not handled by specific error codes listed below.
+ int32 internal constant PAYER_ACCOUNT_NOT_FOUND = 2; //Payer account does not exist.
+ int32 internal constant INVALID_NODE_ACCOUNT = 3; //Node Account provided does not match the node account of the node the transaction was submitted to.
+ int32 internal constant TRANSACTION_EXPIRED = 4; // Pre-Check error when TransactionValidStart + transactionValidDuration is less than current consensus time.
+ int32 internal constant INVALID_TRANSACTION_START = 5; // Transaction start time is greater than current consensus time
+ int32 internal constant INVALID_TRANSACTION_DURATION = 6; //valid transaction duration is a positive non zero number that does not exceed 120 seconds
+ int32 internal constant INVALID_SIGNATURE = 7; // The transaction signature is not valid
+ int32 internal constant MEMO_TOO_LONG = 8; //Transaction memo size exceeded 100 bytes
+ int32 internal constant INSUFFICIENT_TX_FEE = 9; // The fee provided in the transaction is insufficient for this type of transaction
+ int32 internal constant INSUFFICIENT_PAYER_BALANCE = 10; // The payer account has insufficient cryptocurrency to pay the transaction fee
+ int32 internal constant DUPLICATE_TRANSACTION = 11; // This transaction ID is a duplicate of one that was submitted to this node or reached consensus in the last 180 seconds (receipt period)
+ int32 internal constant BUSY = 12; //If API is throttled out
+ int32 internal constant NOT_SUPPORTED = 13; //The API is not currently supported
+
+ int32 internal constant INVALID_FILE_ID = 14; //The file id is invalid or does not exist
+ int32 internal constant INVALID_ACCOUNT_ID = 15; //The account id is invalid or does not exist
+ int32 internal constant INVALID_CONTRACT_ID = 16; //The contract id is invalid or does not exist
+ int32 internal constant INVALID_TRANSACTION_ID = 17; //Transaction id is not valid
+ int32 internal constant RECEIPT_NOT_FOUND = 18; //Receipt for given transaction id does not exist
+ int32 internal constant RECORD_NOT_FOUND = 19; //Record for given transaction id does not exist
+ int32 internal constant INVALID_SOLIDITY_ID = 20; //The solidity id is invalid or entity with this solidity id does not exist
+
+ int32 internal constant UNKNOWN = 21; // The responding node has submitted the transaction to the network. Its final status is still unknown.
+ int32 internal constant SUCCESS = 22; // The transaction succeeded
+ int32 internal constant FAIL_INVALID = 23; // There was a system error and the transaction failed because of invalid request parameters.
+ int32 internal constant FAIL_FEE = 24; // There was a system error while performing fee calculation, reserved for future.
+ int32 internal constant FAIL_BALANCE = 25; // There was a system error while performing balance checks, reserved for future.
+
+ int32 internal constant KEY_REQUIRED = 26; //Key not provided in the transaction body
+ int32 internal constant BAD_ENCODING = 27; //Unsupported algorithm/encoding used for keys in the transaction
+ int32 internal constant INSUFFICIENT_ACCOUNT_BALANCE = 28; //When the account balance is not sufficient for the transfer
+ int32 internal constant INVALID_SOLIDITY_ADDRESS = 29; //During an update transaction when the system is not able to find the Users Solidity address
+
+ int32 internal constant INSUFFICIENT_GAS = 30; //Not enough gas was supplied to execute transaction
+ int32 internal constant CONTRACT_SIZE_LIMIT_EXCEEDED = 31; //contract byte code size is over the limit
+ int32 internal constant LOCAL_CALL_MODIFICATION_EXCEPTION = 32; //local execution (query) is requested for a function which changes state
+ int32 internal constant CONTRACT_REVERT_EXECUTED = 33; //Contract REVERT OPCODE executed
+ int32 internal constant CONTRACT_EXECUTION_EXCEPTION = 34; //For any contract execution related error not handled by specific error codes listed above.
+ int32 internal constant INVALID_RECEIVING_NODE_ACCOUNT = 35; //In Query validation, account with +ve(amount) value should be Receiving node account, the receiver account should be only one account in the list
+ int32 internal constant MISSING_QUERY_HEADER = 36; // Header is missing in Query request
+
+ int32 internal constant ACCOUNT_UPDATE_FAILED = 37; // The update of the account failed
+ int32 internal constant INVALID_KEY_ENCODING = 38; // Provided key encoding was not supported by the system
+ int32 internal constant NULL_SOLIDITY_ADDRESS = 39; // null solidity address
+
+ int32 internal constant CONTRACT_UPDATE_FAILED = 40; // update of the contract failed
+ int32 internal constant INVALID_QUERY_HEADER = 41; // the query header is invalid
+
+ int32 internal constant INVALID_FEE_SUBMITTED = 42; // Invalid fee submitted
+ int32 internal constant INVALID_PAYER_SIGNATURE = 43; // Payer signature is invalid
+
+ int32 internal constant KEY_NOT_PROVIDED = 44; // The keys were not provided in the request.
+ int32 internal constant INVALID_EXPIRATION_TIME = 45; // Expiration time provided in the transaction was invalid.
+ int32 internal constant NO_WACL_KEY = 46; //WriteAccess Control Keys are not provided for the file
+ int32 internal constant FILE_CONTENT_EMPTY = 47; //The contents of file are provided as empty.
+ int32 internal constant INVALID_ACCOUNT_AMOUNTS = 48; // The crypto transfer credit and debit do not sum equal to 0
+ int32 internal constant EMPTY_TRANSACTION_BODY = 49; // Transaction body provided is empty
+ int32 internal constant INVALID_TRANSACTION_BODY = 50; // Invalid transaction body provided
+
+ int32 internal constant INVALID_SIGNATURE_TYPE_MISMATCHING_KEY = 51; // the type of key (base ed25519 key, KeyList, or ThresholdKey) does not match the type of signature (base ed25519 signature, SignatureList, or ThresholdKeySignature)
+ int32 internal constant INVALID_SIGNATURE_COUNT_MISMATCHING_KEY = 52; // the number of key (KeyList, or ThresholdKey) does not match that of signature (SignatureList, or ThresholdKeySignature). e.g. if a keyList has 3 base keys, then the corresponding signatureList should also have 3 base signatures.
+
+ int32 internal constant EMPTY_LIVE_HASH_BODY = 53; // the livehash body is empty
+ int32 internal constant EMPTY_LIVE_HASH = 54; // the livehash data is missing
+ int32 internal constant EMPTY_LIVE_HASH_KEYS = 55; // the keys for a livehash are missing
+ int32 internal constant INVALID_LIVE_HASH_SIZE = 56; // the livehash data is not the output of a SHA-384 digest
+
+ int32 internal constant EMPTY_QUERY_BODY = 57; // the query body is empty
+ int32 internal constant EMPTY_LIVE_HASH_QUERY = 58; // the crypto livehash query is empty
+ int32 internal constant LIVE_HASH_NOT_FOUND = 59; // the livehash is not present
+ int32 internal constant ACCOUNT_ID_DOES_NOT_EXIST = 60; // the account id passed has not yet been created.
+ int32 internal constant LIVE_HASH_ALREADY_EXISTS = 61; // the livehash already exists for a given account
+
+ int32 internal constant INVALID_FILE_WACL = 62; // File WACL keys are invalid
+ int32 internal constant SERIALIZATION_FAILED = 63; // Serialization failure
+ int32 internal constant TRANSACTION_OVERSIZE = 64; // The size of the Transaction is greater than transactionMaxBytes
+ int32 internal constant TRANSACTION_TOO_MANY_LAYERS = 65; // The Transaction has more than 50 levels
+ int32 internal constant CONTRACT_DELETED = 66; //Contract is marked as deleted
+
+ int32 internal constant PLATFORM_NOT_ACTIVE = 67; // the platform node is either disconnected or lagging behind.
+ int32 internal constant KEY_PREFIX_MISMATCH = 68; // one internal key matches more than one prefixes on the signature map
+ int32 internal constant PLATFORM_TRANSACTION_NOT_CREATED = 69; // transaction not created by platform due to large backlog
+ int32 internal constant INVALID_RENEWAL_PERIOD = 70; // auto renewal period is not a positive number of seconds
+ int32 internal constant INVALID_PAYER_ACCOUNT_ID = 71; // the response code when a smart contract id is passed for a crypto API request
+ int32 internal constant ACCOUNT_DELETED = 72; // the account has been marked as deleted
+ int32 internal constant FILE_DELETED = 73; // the file has been marked as deleted
+ int32 internal constant ACCOUNT_REPEATED_IN_ACCOUNT_AMOUNTS = 74; // same accounts repeated in the transfer account list
+ int32 internal constant SETTING_NEGATIVE_ACCOUNT_BALANCE = 75; // attempting to set negative balance value for crypto account
+ int32 internal constant OBTAINER_REQUIRED = 76; // when deleting smart contract that has crypto balance either transfer account or transfer smart contract is required
+ int32 internal constant OBTAINER_SAME_CONTRACT_ID = 77; //when deleting smart contract that has crypto balance you can not use the same contract id as transferContractId as the one being deleted
+ int32 internal constant OBTAINER_DOES_NOT_EXIST = 78; //transferAccountId or transferContractId specified for contract delete does not exist
+ int32 internal constant MODIFYING_IMMUTABLE_CONTRACT = 79; //attempting to modify (update or delete a immutable smart contract, i.e. one created without a admin key)
+ int32 internal constant FILE_SYSTEM_EXCEPTION = 80; //Unexpected exception thrown by file system functions
+ int32 internal constant AUTORENEW_DURATION_NOT_IN_RANGE = 81; // the duration is not a subset of [MINIMUM_AUTORENEW_DURATION,MAXIMUM_AUTORENEW_DURATION]
+ int32 internal constant ERROR_DECODING_BYTESTRING = 82; // Decoding the smart contract binary to a byte array failed. Check that the input is a valid hex string.
+ int32 internal constant CONTRACT_FILE_EMPTY = 83; // File to create a smart contract was of length zero
+ int32 internal constant CONTRACT_BYTECODE_EMPTY = 84; // Bytecode for smart contract is of length zero
+ int32 internal constant INVALID_INITIAL_BALANCE = 85; // Attempt to set negative initial balance
+ int32 internal constant INVALID_RECEIVE_RECORD_THRESHOLD = 86; // [Deprecated]. attempt to set negative receive record threshold
+ int32 internal constant INVALID_SEND_RECORD_THRESHOLD = 87; // [Deprecated]. attempt to set negative send record threshold
+ int32 internal constant ACCOUNT_IS_NOT_GENESIS_ACCOUNT = 88; // Special Account Operations should be performed by only Genesis account, return this code if it is not Genesis Account
+ int32 internal constant PAYER_ACCOUNT_UNAUTHORIZED = 89; // The fee payer account doesn't have permission to submit such Transaction
+ int32 internal constant INVALID_FREEZE_TRANSACTION_BODY = 90; // FreezeTransactionBody is invalid
+ int32 internal constant FREEZE_TRANSACTION_BODY_NOT_FOUND = 91; // FreezeTransactionBody does not exist
+ int32 internal constant TRANSFER_LIST_SIZE_LIMIT_EXCEEDED = 92; //Exceeded the number of accounts (both from and to) allowed for crypto transfer list
+ int32 internal constant RESULT_SIZE_LIMIT_EXCEEDED = 93; // Smart contract result size greater than specified maxResultSize
+ int32 internal constant NOT_SPECIAL_ACCOUNT = 94; //The payer account is not a special account(account 0.0.55)
+ int32 internal constant CONTRACT_NEGATIVE_GAS = 95; // Negative gas was offered in smart contract call
+ int32 internal constant CONTRACT_NEGATIVE_VALUE = 96; // Negative value / initial balance was specified in a smart contract call / create
+ int32 internal constant INVALID_FEE_FILE = 97; // Failed to update fee file
+ int32 internal constant INVALID_EXCHANGE_RATE_FILE = 98; // Failed to update exchange rate file
+ int32 internal constant INSUFFICIENT_LOCAL_CALL_GAS = 99; // Payment tendered for contract local call cannot cover both the fee and the gas
+ int32 internal constant ENTITY_NOT_ALLOWED_TO_DELETE = 100; // Entities with Entity ID below 1000 are not allowed to be deleted
+ int32 internal constant AUTHORIZATION_FAILED = 101; // Violating one of these rules: 1) treasury account can update all entities below 0.0.1000, 2) account 0.0.50 can update all entities from 0.0.51 - 0.0.80, 3) Network Function Master Account A/c 0.0.50 - Update all Network Function accounts & perform all the Network Functions listed below, 4) Network Function Accounts: i) A/c 0.0.55 - Update Address Book files (0.0.101/102), ii) A/c 0.0.56 - Update Fee schedule (0.0.111), iii) A/c 0.0.57 - Update Exchange Rate (0.0.112).
+ int32 internal constant FILE_UPLOADED_PROTO_INVALID = 102; // Fee Schedule Proto uploaded but not valid (append or update is required)
+ int32 internal constant FILE_UPLOADED_PROTO_NOT_SAVED_TO_DISK = 103; // Fee Schedule Proto uploaded but not valid (append or update is required)
+ int32 internal constant FEE_SCHEDULE_FILE_PART_UPLOADED = 104; // Fee Schedule Proto File Part uploaded
+ int32 internal constant EXCHANGE_RATE_CHANGE_LIMIT_EXCEEDED = 105; // The change on Exchange Rate exceeds Exchange_Rate_Allowed_Percentage
+ int32 internal constant MAX_CONTRACT_STORAGE_EXCEEDED = 106; // Contract permanent storage exceeded the currently allowable limit
+ int32 internal constant TRANSFER_ACCOUNT_SAME_AS_DELETE_ACCOUNT = 107; // Transfer Account should not be same as Account to be deleted
+ int32 internal constant TOTAL_LEDGER_BALANCE_INVALID = 108;
+ int32 internal constant EXPIRATION_REDUCTION_NOT_ALLOWED = 110; // The expiration date/time on a smart contract may not be reduced
+ int32 internal constant MAX_GAS_LIMIT_EXCEEDED = 111; //Gas exceeded currently allowable gas limit per transaction
+ int32 internal constant MAX_FILE_SIZE_EXCEEDED = 112; // File size exceeded the currently allowable limit
+
+ int32 internal constant INVALID_TOPIC_ID = 150; // The Topic ID specified is not in the system.
+ int32 internal constant INVALID_ADMIN_KEY = 155; // A provided admin key was invalid.
+ int32 internal constant INVALID_SUBMIT_KEY = 156; // A provided submit key was invalid.
+ int32 internal constant UNAUTHORIZED = 157; // An attempted operation was not authorized (ie - a deleteTopic for a topic with no adminKey).
+ int32 internal constant INVALID_TOPIC_MESSAGE = 158; // A ConsensusService message is empty.
+ int32 internal constant INVALID_AUTORENEW_ACCOUNT = 159; // The autoRenewAccount specified is not a valid, active account.
+ int32 internal constant AUTORENEW_ACCOUNT_NOT_ALLOWED = 160; // An adminKey was not specified on the topic, so there must not be an autoRenewAccount.
+ // The topic has expired, was not automatically renewed, and is in a 7 day grace period before the topic will be
+ // deleted unrecoverably. This error response code will not be returned until autoRenew functionality is supported
+ // by HAPI.
+ int32 internal constant TOPIC_EXPIRED = 162;
+ int32 internal constant INVALID_CHUNK_NUMBER = 163; // chunk number must be from 1 to total (chunks) inclusive.
+ int32 internal constant INVALID_CHUNK_TRANSACTION_ID = 164; // For every chunk, the payer account that is part of initialTransactionID must match the Payer Account of this transaction. The entire initialTransactionID should match the transactionID of the first chunk, but this is not checked or enforced by Hedera except when the chunk number is 1.
+ int32 internal constant ACCOUNT_FROZEN_FOR_TOKEN = 165; // Account is frozen and cannot transact with the token
+ int32 internal constant TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED = 166; // An involved account already has more than tokens.maxPerAccount associations with non-deleted tokens.
+ int32 internal constant INVALID_TOKEN_ID = 167; // The token is invalid or does not exist
+ int32 internal constant INVALID_TOKEN_DECIMALS = 168; // Invalid token decimals
+ int32 internal constant INVALID_TOKEN_INITIAL_SUPPLY = 169; // Invalid token initial supply
+ int32 internal constant INVALID_TREASURY_ACCOUNT_FOR_TOKEN = 170; // Treasury Account does not exist or is deleted
+ int32 internal constant INVALID_TOKEN_SYMBOL = 171; // Token Symbol is not UTF-8 capitalized alphabetical string
+ int32 internal constant TOKEN_HAS_NO_FREEZE_KEY = 172; // Freeze key is not set on token
+ int32 internal constant TRANSFERS_NOT_ZERO_SUM_FOR_TOKEN = 173; // Amounts in transfer list are not net zero
+ int32 internal constant MISSING_TOKEN_SYMBOL = 174; // A token symbol was not provided
+ int32 internal constant TOKEN_SYMBOL_TOO_LONG = 175; // The provided token symbol was too long
+ int32 internal constant ACCOUNT_KYC_NOT_GRANTED_FOR_TOKEN = 176; // KYC must be granted and account does not have KYC granted
+ int32 internal constant TOKEN_HAS_NO_KYC_KEY = 177; // KYC key is not set on token
+ int32 internal constant INSUFFICIENT_TOKEN_BALANCE = 178; // Token balance is not sufficient for the transaction
+ int32 internal constant TOKEN_WAS_DELETED = 179; // Token transactions cannot be executed on deleted token
+ int32 internal constant TOKEN_HAS_NO_SUPPLY_KEY = 180; // Supply key is not set on token
+ int32 internal constant TOKEN_HAS_NO_WIPE_KEY = 181; // Wipe key is not set on token
+ int32 internal constant INVALID_TOKEN_MINT_AMOUNT = 182; // The requested token mint amount would cause an invalid total supply
+ int32 internal constant INVALID_TOKEN_BURN_AMOUNT = 183; // The requested token burn amount would cause an invalid total supply
+ int32 internal constant TOKEN_NOT_ASSOCIATED_TO_ACCOUNT = 184; // A required token-account relationship is missing
+ int32 internal constant CANNOT_WIPE_TOKEN_TREASURY_ACCOUNT = 185; // The target of a wipe operation was the token treasury account
+ int32 internal constant INVALID_KYC_KEY = 186; // The provided KYC key was invalid.
+ int32 internal constant INVALID_WIPE_KEY = 187; // The provided wipe key was invalid.
+ int32 internal constant INVALID_FREEZE_KEY = 188; // The provided freeze key was invalid.
+ int32 internal constant INVALID_SUPPLY_KEY = 189; // The provided supply key was invalid.
+ int32 internal constant MISSING_TOKEN_NAME = 190; // Token Name is not provided
+ int32 internal constant TOKEN_NAME_TOO_LONG = 191; // Token Name is too long
+ int32 internal constant INVALID_WIPING_AMOUNT = 192; // The provided wipe amount must not be negative, zero or bigger than the token holder balance
+ int32 internal constant TOKEN_IS_IMMUTABLE = 193; // Token does not have Admin key set, thus update/delete transactions cannot be performed
+ int32 internal constant TOKEN_ALREADY_ASSOCIATED_TO_ACCOUNT = 194; // An associateToken operation specified a token already associated to the account
+ int32 internal constant TRANSACTION_REQUIRES_ZERO_TOKEN_BALANCES = 195; // An attempted operation is invalid until all token balances for the target account are zero
+ int32 internal constant ACCOUNT_IS_TREASURY = 196; // An attempted operation is invalid because the account is a treasury
+ int32 internal constant TOKEN_ID_REPEATED_IN_TOKEN_LIST = 197; // Same TokenIDs present in the token list
+ int32 internal constant TOKEN_TRANSFER_LIST_SIZE_LIMIT_EXCEEDED = 198; // Exceeded the number of token transfers (both from and to) allowed for token transfer list
+ int32 internal constant EMPTY_TOKEN_TRANSFER_BODY = 199; // TokenTransfersTransactionBody has no TokenTransferList
+ int32 internal constant EMPTY_TOKEN_TRANSFER_ACCOUNT_AMOUNTS = 200; // TokenTransfersTransactionBody has a TokenTransferList with no AccountAmounts
+ int32 internal constant INVALID_SCHEDULE_ID = 201; // The Scheduled entity does not exist; or has now expired, been deleted, or been executed
+ int32 internal constant SCHEDULE_IS_IMMUTABLE = 202; // The Scheduled entity cannot be modified. Admin key not set
+ int32 internal constant INVALID_SCHEDULE_PAYER_ID = 203; // The provided Scheduled Payer does not exist
+ int32 internal constant INVALID_SCHEDULE_ACCOUNT_ID = 204; // The Schedule Create Transaction TransactionID account does not exist
+ int32 internal constant NO_NEW_VALID_SIGNATURES = 205; // The provided sig map did not contain any new valid signatures from required signers of the scheduled transaction
+ int32 internal constant UNRESOLVABLE_REQUIRED_SIGNERS = 206; // The required signers for a scheduled transaction cannot be resolved, for example because they do not exist or have been deleted
+ int32 internal constant SCHEDULED_TRANSACTION_NOT_IN_WHITELIST = 207; // Only whitelisted transaction types may be scheduled
+ int32 internal constant SOME_SIGNATURES_WERE_INVALID = 208; // At least one of the signatures in the provided sig map did not represent a valid signature for any required signer
+ int32 internal constant TRANSACTION_ID_FIELD_NOT_ALLOWED = 209; // The scheduled field in the TransactionID may not be set to true
+ int32 internal constant IDENTICAL_SCHEDULE_ALREADY_CREATED = 210; // A schedule already exists with the same identifying fields of an attempted ScheduleCreate (that is, all fields other than scheduledPayerAccountID)
+ int32 internal constant INVALID_ZERO_BYTE_IN_STRING = 211; // A string field in the transaction has a UTF-8 encoding with the prohibited zero byte
+ int32 internal constant SCHEDULE_ALREADY_DELETED = 212; // A schedule being signed or deleted has already been deleted
+ int32 internal constant SCHEDULE_ALREADY_EXECUTED = 213; // A schedule being signed or deleted has already been executed
+ int32 internal constant MESSAGE_SIZE_TOO_LARGE = 214; // ConsensusSubmitMessage request's message size is larger than allowed.
+ int32 internal constant OPERATION_REPEATED_IN_BUCKET_GROUPS = 215; // An operation was assigned to more than one throttle group in a given bucket
+ int32 internal constant BUCKET_CAPACITY_OVERFLOW = 216; // The capacity needed to satisfy all opsPerSec groups in a bucket overflowed a signed 8-byte integral type
+ int32 internal constant NODE_CAPACITY_NOT_SUFFICIENT_FOR_OPERATION = 217; // Given the network size in the address book, the node-level capacity for an operation would never be enough to accept a single request; usually means a bucket burstPeriod should be increased
+ int32 internal constant BUCKET_HAS_NO_THROTTLE_GROUPS = 218; // A bucket was defined without any throttle groups
+ int32 internal constant THROTTLE_GROUP_HAS_ZERO_OPS_PER_SEC = 219; // A throttle group was granted zero opsPerSec
+ int32 internal constant SUCCESS_BUT_MISSING_EXPECTED_OPERATION = 220; // The throttle definitions file was updated, but some supported operations were not assigned a bucket
+ int32 internal constant UNPARSEABLE_THROTTLE_DEFINITIONS = 221; // The new contents for the throttle definitions system file were not valid protobuf
+ int32 internal constant INVALID_THROTTLE_DEFINITIONS = 222; // The new throttle definitions system file were invalid, and no more specific error could be divined
+ int32 internal constant ACCOUNT_EXPIRED_AND_PENDING_REMOVAL = 223; // The transaction references an account which has passed its expiration without renewal funds available, and currently remains in the ledger only because of the grace period given to expired entities
+ int32 internal constant INVALID_TOKEN_MAX_SUPPLY = 224; // Invalid token max supply
+ int32 internal constant INVALID_TOKEN_NFT_SERIAL_NUMBER = 225; // Invalid token nft serial number
+ int32 internal constant INVALID_NFT_ID = 226; // Invalid nft id
+ int32 internal constant METADATA_TOO_LONG = 227; // Nft metadata is too long
+ int32 internal constant BATCH_SIZE_LIMIT_EXCEEDED = 228; // Repeated operations count exceeds the limit
+ int32 internal constant INVALID_QUERY_RANGE = 229; // The range of data to be gathered is out of the set boundaries
+ int32 internal constant FRACTION_DIVIDES_BY_ZERO = 230; // A custom fractional fee set a denominator of zero
+ int32 internal constant INSUFFICIENT_PAYER_BALANCE_FOR_CUSTOM_FEE = 231; // The transaction payer could not afford a custom fee
+ int32 internal constant CUSTOM_FEES_LIST_TOO_LONG = 232; // More than 10 custom fees were specified
+ int32 internal constant INVALID_CUSTOM_FEE_COLLECTOR = 233; // Any of the feeCollector accounts for customFees is invalid
+ int32 internal constant INVALID_TOKEN_ID_IN_CUSTOM_FEES = 234; // Any of the token Ids in customFees is invalid
+ int32 internal constant TOKEN_NOT_ASSOCIATED_TO_FEE_COLLECTOR = 235; // Any of the token Ids in customFees are not associated to feeCollector
+ int32 internal constant TOKEN_MAX_SUPPLY_REACHED = 236; // A token cannot have more units minted due to its configured supply ceiling
+ int32 internal constant SENDER_DOES_NOT_OWN_NFT_SERIAL_NO = 237; // The transaction attempted to move an NFT serial number from an account other than its owner
+ int32 internal constant CUSTOM_FEE_NOT_FULLY_SPECIFIED = 238; // A custom fee schedule entry did not specify either a fixed or fractional fee
+ int32 internal constant CUSTOM_FEE_MUST_BE_POSITIVE = 239; // Only positive fees may be assessed at this time
+ int32 internal constant TOKEN_HAS_NO_FEE_SCHEDULE_KEY = 240; // Fee schedule key is not set on token
+ int32 internal constant CUSTOM_FEE_OUTSIDE_NUMERIC_RANGE = 241; // A fractional custom fee exceeded the range of a 64-bit signed integer
+ int32 internal constant ROYALTY_FRACTION_CANNOT_EXCEED_ONE = 242; // A royalty cannot exceed the total fungible value exchanged for an NFT
+ int32 internal constant FRACTIONAL_FEE_MAX_AMOUNT_LESS_THAN_MIN_AMOUNT = 243; // Each fractional custom fee must have its maximum_amount, if specified, at least its minimum_amount
+ int32 internal constant CUSTOM_SCHEDULE_ALREADY_HAS_NO_FEES = 244; // A fee schedule update tried to clear the custom fees from a token whose fee schedule was already empty
+ int32 internal constant CUSTOM_FEE_DENOMINATION_MUST_BE_FUNGIBLE_COMMON = 245; // Only tokens of type FUNGIBLE_COMMON can be used to as fee schedule denominations
+ int32 internal constant CUSTOM_FRACTIONAL_FEE_ONLY_ALLOWED_FOR_FUNGIBLE_COMMON = 246; // Only tokens of type FUNGIBLE_COMMON can have fractional fees
+ int32 internal constant INVALID_CUSTOM_FEE_SCHEDULE_KEY = 247; // The provided custom fee schedule key was invalid
+ int32 internal constant INVALID_TOKEN_MINT_METADATA = 248; // The requested token mint metadata was invalid
+ int32 internal constant INVALID_TOKEN_BURN_METADATA = 249; // The requested token burn metadata was invalid
+ int32 internal constant CURRENT_TREASURY_STILL_OWNS_NFTS = 250; // The treasury for a unique token cannot be changed until it owns no NFTs
+ int32 internal constant ACCOUNT_STILL_OWNS_NFTS = 251; // An account cannot be dissociated from a unique token if it owns NFTs for the token
+ int32 internal constant TREASURY_MUST_OWN_BURNED_NFT = 252; // A NFT can only be burned when owned by the unique token's treasury
+ int32 internal constant ACCOUNT_DOES_NOT_OWN_WIPED_NFT = 253; // An account did not own the NFT to be wiped
+ int32 internal constant ACCOUNT_AMOUNT_TRANSFERS_ONLY_ALLOWED_FOR_FUNGIBLE_COMMON = 254; // An AccountAmount token transfers list referenced a token type other than FUNGIBLE_COMMON
+ int32 internal constant MAX_NFTS_IN_PRICE_REGIME_HAVE_BEEN_MINTED = 255; // All the NFTs allowed in the current price regime have already been minted
+ int32 internal constant PAYER_ACCOUNT_DELETED = 256; // The payer account has been marked as deleted
+ int32 internal constant CUSTOM_FEE_CHARGING_EXCEEDED_MAX_RECURSION_DEPTH = 257; // The reference chain of custom fees for a transferred token exceeded the maximum length of 2
+ int32 internal constant CUSTOM_FEE_CHARGING_EXCEEDED_MAX_ACCOUNT_AMOUNTS = 258; // More than 20 balance adjustments were to satisfy a CryptoTransfer and its implied custom fee payments
+ int32 internal constant INSUFFICIENT_SENDER_ACCOUNT_BALANCE_FOR_CUSTOM_FEE = 259; // The sender account in the token transfer transaction could not afford a custom fee
+ int32 internal constant SERIAL_NUMBER_LIMIT_REACHED = 260; // Currently no more than 4,294,967,295 NFTs may be minted for a given unique token type
+ int32 internal constant CUSTOM_ROYALTY_FEE_ONLY_ALLOWED_FOR_NON_FUNGIBLE_UNIQUE = 261; // Only tokens of type NON_FUNGIBLE_UNIQUE can have royalty fees
+ int32 internal constant NO_REMAINING_AUTOMATIC_ASSOCIATIONS = 262; // The account has reached the limit on the automatic associations count.
+ int32 internal constant EXISTING_AUTOMATIC_ASSOCIATIONS_EXCEED_GIVEN_LIMIT = 263; // Already existing automatic associations are more than the new maximum automatic associations.
+ int32 internal constant REQUESTED_NUM_AUTOMATIC_ASSOCIATIONS_EXCEEDS_ASSOCIATION_LIMIT = 264; // Cannot set the number of automatic associations for an account more than the maximum allowed tokens.maxPerAccount.
+ int32 internal constant TOKEN_IS_PAUSED = 265; // Token is paused. This Token cannot be a part of any kind of Transaction until unpaused.
+ int32 internal constant TOKEN_HAS_NO_PAUSE_KEY = 266; // Pause key is not set on token
+ int32 internal constant INVALID_PAUSE_KEY = 267; // The provided pause key was invalid
+ int32 internal constant FREEZE_UPDATE_FILE_DOES_NOT_EXIST = 268; // The update file in a freeze transaction body must exist.
+ int32 internal constant FREEZE_UPDATE_FILE_HASH_DOES_NOT_MATCH = 269; // The hash of the update file in a freeze transaction body must match the in-memory hash.
+ int32 internal constant NO_UPGRADE_HAS_BEEN_PREPARED = 270; // A FREEZE_UPGRADE transaction was handled with no previous update prepared.
+ int32 internal constant NO_FREEZE_IS_SCHEDULED = 271; // A FREEZE_ABORT transaction was handled with no scheduled freeze.
+ int32 internal constant UPDATE_FILE_HASH_CHANGED_SINCE_PREPARE_UPGRADE = 272; // The update file hash when handling a FREEZE_UPGRADE transaction differs from the file hash at the time of handling the PREPARE_UPGRADE transaction.
+ int32 internal constant FREEZE_START_TIME_MUST_BE_FUTURE = 273; // The given freeze start time was in the (consensus) past.
+ int32 internal constant PREPARED_UPDATE_FILE_IS_IMMUTABLE = 274; // The prepared update file cannot be updated or appended until either the upgrade has been completed, or a FREEZE_ABORT has been handled.
+ int32 internal constant FREEZE_ALREADY_SCHEDULED = 275; // Once a freeze is scheduled, it must be aborted before any other type of freeze can be performed.
+ int32 internal constant FREEZE_UPGRADE_IN_PROGRESS = 276; // If an NMT upgrade has been prepared, the following operation must be a FREEZE_UPGRADE (To issue a FREEZE_ONLY, submit a FREEZE_ABORT first.)
+ int32 internal constant UPDATE_FILE_ID_DOES_NOT_MATCH_PREPARED = 277; // If an NMT upgrade has been prepared, the subsequent FREEZE_UPGRADE transaction must confirm the id of the file to be used in the upgrade.
+ int32 internal constant UPDATE_FILE_HASH_DOES_NOT_MATCH_PREPARED = 278; // If an NMT upgrade has been prepared, the subsequent FREEZE_UPGRADE transaction must confirm the hash of the file to be used in the upgrade.
+ int32 internal constant CONSENSUS_GAS_EXHAUSTED = 279; // Consensus throttle did not allow execution of this transaction. System is throttled at consensus level.
+ int32 internal constant REVERTED_SUCCESS = 280; // A precompiled contract succeeded, but was later reverted.
+ int32 internal constant MAX_STORAGE_IN_PRICE_REGIME_HAS_BEEN_USED = 281; // All contract storage allocated to the current price regime has been consumed.
+ int32 internal constant INVALID_ALIAS_KEY = 282; // An alias used in a CryptoTransfer transaction is not the serialization of a primitive Key message -- that is, a Key with a single Ed25519 or ECDSA(secp256k1) public key and no unknown protobuf fields.
+ int32 internal constant UNEXPECTED_TOKEN_DECIMALS = 283; // A fungible token transfer expected a different number of decimals than the involved type actually has.
+ int32 internal constant INVALID_PROXY_ACCOUNT_ID = 284; // [Deprecated] The proxy account id is invalid or does not exist.
+ int32 internal constant INVALID_TRANSFER_ACCOUNT_ID = 285; // The transfer account id in CryptoDelete transaction is invalid or does not exist.
+ int32 internal constant INVALID_FEE_COLLECTOR_ACCOUNT_ID = 286; // The fee collector account id in TokenFeeScheduleUpdate is invalid or does not exist.
+ int32 internal constant ALIAS_IS_IMMUTABLE = 287; // The alias already set on an account cannot be updated using CryptoUpdate transaction.
+ int32 internal constant SPENDER_ACCOUNT_SAME_AS_OWNER = 288; // An approved allowance specifies a spender account that is the same as the hbar/token owner account.
+ int32 internal constant AMOUNT_EXCEEDS_TOKEN_MAX_SUPPLY = 289; // The establishment or adjustment of an approved allowance cause the token allowance to exceed the token maximum supply.
+ int32 internal constant NEGATIVE_ALLOWANCE_AMOUNT = 290; // The specified amount for an approved allowance cannot be negative.
+ int32 internal constant CANNOT_APPROVE_FOR_ALL_FUNGIBLE_COMMON = 291; // [Deprecated] The approveForAll flag cannot be set for a fungible token.
+ int32 internal constant SPENDER_DOES_NOT_HAVE_ALLOWANCE = 292; // The spender does not have an existing approved allowance with the hbar/token owner.
+ int32 internal constant AMOUNT_EXCEEDS_ALLOWANCE = 293; // The transfer amount exceeds the current approved allowance for the spender account.
+ int32 internal constant MAX_ALLOWANCES_EXCEEDED = 294; // The payer account of an approveAllowances or adjustAllowance transaction is attempting to go beyond the maximum allowed number of allowances.
+ int32 internal constant EMPTY_ALLOWANCES = 295; // No allowances have been specified in the approval transaction.
+ int32 internal constant SPENDER_ACCOUNT_REPEATED_IN_ALLOWANCES = 296; // [Deprecated] Spender is repeated more than once in Crypto or Token or NFT allowance lists in a single CryptoApproveAllowance transaction.
+ int32 internal constant REPEATED_SERIAL_NUMS_IN_NFT_ALLOWANCES = 297; // [Deprecated] Serial numbers are repeated in nft allowance for a single spender account
+ int32 internal constant FUNGIBLE_TOKEN_IN_NFT_ALLOWANCES = 298; // Fungible common token used in NFT allowances
+ int32 internal constant NFT_IN_FUNGIBLE_TOKEN_ALLOWANCES = 299; // Non fungible token used in fungible token allowances
+ int32 internal constant INVALID_ALLOWANCE_OWNER_ID = 300; // The account id specified as the owner is invalid or does not exist.
+ int32 internal constant INVALID_ALLOWANCE_SPENDER_ID = 301; // The account id specified as the spender is invalid or does not exist.
+ int32 internal constant REPEATED_ALLOWANCES_TO_DELETE = 302; // [Deprecated] If the CryptoDeleteAllowance transaction has repeated crypto or token or Nft allowances to delete.
+ int32 internal constant INVALID_DELEGATING_SPENDER = 303; // If the account Id specified as the delegating spender is invalid or does not exist.
+ int32 internal constant DELEGATING_SPENDER_CANNOT_GRANT_APPROVE_FOR_ALL = 304; // The delegating Spender cannot grant approveForAll allowance on a NFT token type for another spender.
+ int32 internal constant DELEGATING_SPENDER_DOES_NOT_HAVE_APPROVE_FOR_ALL = 305; // The delegating Spender cannot grant allowance on a NFT serial for another spender as it doesnt not have approveForAll granted on token-owner.
+ int32 internal constant SCHEDULE_EXPIRATION_TIME_TOO_FAR_IN_FUTURE = 306; // The scheduled transaction could not be created because it's expiration_time was too far in the future.
+ int32 internal constant SCHEDULE_EXPIRATION_TIME_MUST_BE_HIGHER_THAN_CONSENSUS_TIME = 307; // The scheduled transaction could not be created because it's expiration_time was less than or equal to the consensus time.
+ int32 internal constant SCHEDULE_FUTURE_THROTTLE_EXCEEDED = 308; // The scheduled transaction could not be created because it would cause throttles to be violated on the specified expiration_time.
+ int32 internal constant SCHEDULE_FUTURE_GAS_LIMIT_EXCEEDED = 309; // The scheduled transaction could not be created because it would cause the gas limit to be violated on the specified expiration_time.
+ int32 internal constant INVALID_ETHEREUM_TRANSACTION = 310; // The ethereum transaction either failed parsing or failed signature validation, or some other EthereumTransaction error not covered by another response code.
+ int32 internal constant WRONG_CHAIN_ID = 311; // EthereumTransaction was signed against a chainId that this network does not support.
+ int32 internal constant WRONG_NONCE = 312; // This transaction specified an ethereumNonce that is not the current ethereumNonce of the account.
+ int32 internal constant ACCESS_LIST_UNSUPPORTED = 313; // The ethereum transaction specified an access list, which the network does not support.
+ int32 internal constant SCHEDULE_PENDING_EXPIRATION = 314; // A schedule being signed or deleted has passed it's expiration date and is pending execution if needed and then expiration.
+ int32 internal constant CONTRACT_IS_TOKEN_TREASURY = 315; // A selfdestruct or ContractDelete targeted a contract that is a token treasury.
+ int32 internal constant CONTRACT_HAS_NON_ZERO_TOKEN_BALANCES = 316; // A selfdestruct or ContractDelete targeted a contract with non-zero token balances.
+ int32 internal constant CONTRACT_EXPIRED_AND_PENDING_REMOVAL = 317; // A contract referenced by a transaction is "detached"; that is, expired and lacking any hbar funds for auto-renewal payment---but still within its post-expiry grace period.
+ int32 internal constant CONTRACT_HAS_NO_AUTO_RENEW_ACCOUNT = 318; // A ContractUpdate requested removal of a contract's auto-renew account, but that contract has no auto-renew account.
+ int32 internal constant PERMANENT_REMOVAL_REQUIRES_SYSTEM_INITIATION = 319; // A delete transaction submitted via HAPI set permanent_removal=true
+ int32 internal constant PROXY_ACCOUNT_ID_FIELD_IS_DEPRECATED = 320; // A CryptoCreate or ContractCreate used the deprecated proxyAccountID field.
+ int32 internal constant SELF_STAKING_IS_NOT_ALLOWED = 321; // An account set the staked_account_id to itself in CryptoUpdate or ContractUpdate transactions.
+ int32 internal constant INVALID_STAKING_ID = 322; // The staking account id or staking node id given is invalid or does not exist.
+ int32 internal constant STAKING_NOT_ENABLED = 323; // Native staking, while implemented, has not yet enabled by the council.
+ int32 internal constant INVALID_PRNG_RANGE = 324; // The range provided in UtilPrng transaction is negative.
+ int32 internal constant MAX_ENTITIES_IN_PRICE_REGIME_HAVE_BEEN_CREATED = 325; // The maximum number of entities allowed in the current price regime have been created.
+ int32 internal constant INVALID_FULL_PREFIX_SIGNATURE_FOR_PRECOMPILE = 326; // The full prefix signature for precompile is not valid
+ int32 internal constant INSUFFICIENT_BALANCES_FOR_STORAGE_RENT = 327; // The combined balances of a contract and its auto-renew account (if any) did not cover the rent charged for net new storage used in a transaction.
+ int32 internal constant MAX_CHILD_RECORDS_EXCEEDED = 328; // A contract transaction tried to use more than the allowed number of child records, via either system contract records or internal contract creations.
+ int32 internal constant INSUFFICIENT_BALANCES_FOR_RENEWAL_FEES = 329; // The combined balances of a contract and its auto-renew account (if any) or balance of an account did not cover the auto-renewal fees in a transaction.
+}
\ No newline at end of file
diff --git a/tests/unit/utils/solc/hts/HederaTokenService.sol b/tests/unit/utils/solc/hts/HederaTokenService.sol
new file mode 100644
index 000000000..b83cc8204
--- /dev/null
+++ b/tests/unit/utils/solc/hts/HederaTokenService.sol
@@ -0,0 +1,743 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity >=0.5.0 <0.9.0;
+pragma experimental ABIEncoderV2;
+
+import "./HederaResponseCodes.sol";
+import "./IHederaTokenService.sol";
+
+abstract contract HederaTokenService {
+ address constant precompileAddress = address(0x167);
+ // 90 days in seconds
+ int32 constant defaultAutoRenewPeriod = 7776000;
+
+ modifier nonEmptyExpiry(IHederaTokenService.HederaToken memory token)
+ {
+ if (token.expiry.second == 0 && token.expiry.autoRenewPeriod == 0) {
+ token.expiry.autoRenewPeriod = defaultAutoRenewPeriod;
+ }
+ _;
+ }
+
+ /// Performs transfers among combinations of tokens and hbars
+ /// @param transferList the list of hbar transfers to do
+ /// @param tokenTransfers the list of transfers to do
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @custom:version 0.3.0 the signature of the previous version was cryptoTransfer(TokenTransferList[] memory tokenTransfers)
+ function cryptoTransfer(IHederaTokenService.TransferList memory transferList, IHederaTokenService.TokenTransferList[] memory tokenTransfers) internal
+ returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.cryptoTransfer.selector, transferList, tokenTransfers));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Performs transfers among combinations of tokens and hbars
+ /// @param transferList the list of hbar transfers to do
+ /// @param tokenTransfers the list of transfers to do
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @custom:version 0.3.0 the signature of the previous version was cryptoTransfer(TokenTransferList[] memory tokenTransfers)
+ function delegateCryptoTransfer(IHederaTokenService.TransferList memory transferList, IHederaTokenService.TokenTransferList[] memory tokenTransfers) internal
+ returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.delegatecall(
+ abi.encodeWithSelector(IHederaTokenService.cryptoTransfer.selector, transferList, tokenTransfers));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Mints an amount of the token to the defined treasury account
+ /// @param token The token for which to mint tokens. If token does not exist, transaction results in
+ /// INVALID_TOKEN_ID
+ /// @param amount Applicable to tokens of type FUNGIBLE_COMMON. The amount to mint to the Treasury Account.
+ /// Amount must be a positive non-zero number represented in the lowest denomination of the
+ /// token. The new supply must be lower than 2^63.
+ /// @param metadata Applicable to tokens of type NON_FUNGIBLE_UNIQUE. A list of metadata that are being created.
+ /// Maximum allowed size of each metadata is 100 bytes
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return newTotalSupply The new supply of tokens. For NFTs it is the total count of NFTs
+ /// @return serialNumbers If the token is an NFT the newly generate serial numbers, otherwise empty.
+ function mintToken(address token, int64 amount, bytes[] memory metadata) internal
+ returns (int responseCode, int64 newTotalSupply, int64[] memory serialNumbers)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.mintToken.selector,
+ token, amount, metadata));
+ (responseCode, newTotalSupply, serialNumbers) =
+ success
+ ? abi.decode(result, (int32, int64, int64[]))
+ : (HederaResponseCodes.UNKNOWN, int64(0), new int64[](0));
+ }
+
+ /// Burns an amount of the token from the defined treasury account
+ /// @param token The token for which to burn tokens. If token does not exist, transaction results in
+ /// INVALID_TOKEN_ID
+ /// @param amount Applicable to tokens of type FUNGIBLE_COMMON. The amount to burn from the Treasury Account.
+ /// Amount must be a positive non-zero number, not bigger than the token balance of the treasury
+ /// account (0; balance], represented in the lowest denomination.
+ /// @param serialNumbers Applicable to tokens of type NON_FUNGIBLE_UNIQUE. The list of serial numbers to be burned.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return newTotalSupply The new supply of tokens. For NFTs it is the total count of NFTs
+ function burnToken(address token, int64 amount, int64[] memory serialNumbers) internal
+ returns (int responseCode, int64 newTotalSupply)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.burnToken.selector,
+ token, amount, serialNumbers));
+ (responseCode, newTotalSupply) =
+ success
+ ? abi.decode(result, (int32, int64))
+ : (HederaResponseCodes.UNKNOWN, int64(0));
+ }
+
+ /// Associates the provided account with the provided tokens. Must be signed by the provided
+ /// Account's key or called from the accounts contract key
+ /// If the provided account is not found, the transaction will resolve to INVALID_ACCOUNT_ID.
+ /// If the provided account has been deleted, the transaction will resolve to ACCOUNT_DELETED.
+ /// If any of the provided tokens is not found, the transaction will resolve to INVALID_TOKEN_REF.
+ /// If any of the provided tokens has been deleted, the transaction will resolve to TOKEN_WAS_DELETED.
+ /// If an association between the provided account and any of the tokens already exists, the
+ /// transaction will resolve to TOKEN_ALREADY_ASSOCIATED_TO_ACCOUNT.
+ /// If the provided account's associations count exceed the constraint of maximum token associations
+ /// per account, the transaction will resolve to TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED.
+ /// On success, associations between the provided account and tokens are made and the account is
+ /// ready to interact with the tokens.
+ /// @param account The account to be associated with the provided tokens
+ /// @param tokens The tokens to be associated with the provided account. In the case of NON_FUNGIBLE_UNIQUE
+ /// Type, once an account is associated, it can hold any number of NFTs (serial numbers) of that
+ /// token type
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function associateTokens(address account, address[] memory tokens) internal returns (int responseCode) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.associateTokens.selector,
+ account, tokens));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ function associateToken(address account, address token) internal returns (int responseCode) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.associateToken.selector,
+ account, token));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Dissociates the provided account with the provided tokens. Must be signed by the provided
+ /// Account's key.
+ /// If the provided account is not found, the transaction will resolve to INVALID_ACCOUNT_ID.
+ /// If the provided account has been deleted, the transaction will resolve to ACCOUNT_DELETED.
+ /// If any of the provided tokens is not found, the transaction will resolve to INVALID_TOKEN_REF.
+ /// If any of the provided tokens has been deleted, the transaction will resolve to TOKEN_WAS_DELETED.
+ /// If an association between the provided account and any of the tokens does not exist, the
+ /// transaction will resolve to TOKEN_NOT_ASSOCIATED_TO_ACCOUNT.
+ /// If a token has not been deleted and has not expired, and the user has a nonzero balance, the
+ /// transaction will resolve to TRANSACTION_REQUIRES_ZERO_TOKEN_BALANCES.
+ /// If a fungible token has expired, the user can disassociate even if their token balance is
+ /// not zero.
+ /// If a non fungible token has expired, the user can not disassociate if their token
+ /// balance is not zero. The transaction will resolve to TRANSACTION_REQUIRED_ZERO_TOKEN_BALANCES.
+ /// On success, associations between the provided account and tokens are removed.
+ /// @param account The account to be dissociated from the provided tokens
+ /// @param tokens The tokens to be dissociated from the provided account.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function dissociateTokens(address account, address[] memory tokens) internal returns (int responseCode) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.dissociateTokens.selector,
+ account, tokens));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ function dissociateToken(address account, address token) internal returns (int responseCode) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.dissociateToken.selector,
+ account, token));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Creates a Fungible Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @param initialTotalSupply Specifies the initial supply of tokens to be put in circulation. The
+ /// initial supply is sent to the Treasury Account. The supply is in the lowest denomination possible.
+ /// @param decimals the number of decimal places a token is divisible by
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createFungibleToken(
+ IHederaTokenService.HederaToken memory token,
+ int64 initialTotalSupply,
+ int32 decimals) nonEmptyExpiry(token)
+ internal returns (int responseCode, address tokenAddress) {
+ (bool success, bytes memory result) = precompileAddress.call{value : msg.value}(
+ abi.encodeWithSelector(IHederaTokenService.createFungibleToken.selector,
+ token, initialTotalSupply, decimals));
+
+
+ (responseCode, tokenAddress) = success ? abi.decode(result, (int32, address)) : (HederaResponseCodes.UNKNOWN, address(0));
+ }
+
+ /// Creates a Fungible Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @param initialTotalSupply Specifies the initial supply of tokens to be put in circulation. The
+ /// initial supply is sent to the Treasury Account. The supply is in the lowest denomination possible.
+ /// @param decimals the number of decimal places a token is divisible by
+ /// @param fixedFees list of fixed fees to apply to the token
+ /// @param fractionalFees list of fractional fees to apply to the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createFungibleTokenWithCustomFees(
+ IHederaTokenService.HederaToken memory token,
+ int64 initialTotalSupply,
+ int32 decimals,
+ IHederaTokenService.FixedFee[] memory fixedFees,
+ IHederaTokenService.FractionalFee[] memory fractionalFees) nonEmptyExpiry(token)
+ internal returns (int responseCode, address tokenAddress) {
+ (bool success, bytes memory result) = precompileAddress.call{value : msg.value}(
+ abi.encodeWithSelector(IHederaTokenService.createFungibleTokenWithCustomFees.selector,
+ token, initialTotalSupply, decimals, fixedFees, fractionalFees));
+ (responseCode, tokenAddress) = success ? abi.decode(result, (int32, address)) : (HederaResponseCodes.UNKNOWN, address(0));
+ }
+
+ /// Creates an Non Fungible Unique Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createNonFungibleToken(IHederaTokenService.HederaToken memory token) nonEmptyExpiry(token)
+ internal returns (int responseCode, address tokenAddress) {
+ (bool success, bytes memory result) = precompileAddress.call{value : msg.value}(
+ abi.encodeWithSelector(IHederaTokenService.createNonFungibleToken.selector, token));
+ (responseCode, tokenAddress) = success ? abi.decode(result, (int32, address)) : (HederaResponseCodes.UNKNOWN, address(0));
+ }
+
+ /// Creates an Non Fungible Unique Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @param fixedFees list of fixed fees to apply to the token
+ /// @param royaltyFees list of royalty fees to apply to the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createNonFungibleTokenWithCustomFees(
+ IHederaTokenService.HederaToken memory token,
+ IHederaTokenService.FixedFee[] memory fixedFees,
+ IHederaTokenService.RoyaltyFee[] memory royaltyFees) nonEmptyExpiry(token)
+ internal returns (int responseCode, address tokenAddress) {
+ (bool success, bytes memory result) = precompileAddress.call{value : msg.value}(
+ abi.encodeWithSelector(IHederaTokenService.createNonFungibleTokenWithCustomFees.selector,
+ token, fixedFees, royaltyFees));
+ (responseCode, tokenAddress) = success ? abi.decode(result, (int32, address)) : (HederaResponseCodes.UNKNOWN, address(0));
+ }
+
+ /// Retrieves fungible specific token info for a fungible token
+ /// @param token The ID of the token as a solidity address
+ function getFungibleTokenInfo(address token) internal returns (int responseCode, IHederaTokenService.FungibleTokenInfo memory tokenInfo) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getFungibleTokenInfo.selector, token));
+ IHederaTokenService.FungibleTokenInfo memory defaultTokenInfo;
+ (responseCode, tokenInfo) = success ? abi.decode(result, (int32, IHederaTokenService.FungibleTokenInfo)) : (HederaResponseCodes.UNKNOWN, defaultTokenInfo);
+ }
+
+ /// Retrieves general token info for a given token
+ /// @param token The ID of the token as a solidity address
+ function getTokenInfo(address token) internal returns (int responseCode, IHederaTokenService.TokenInfo memory tokenInfo) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenInfo.selector, token));
+ IHederaTokenService.TokenInfo memory defaultTokenInfo;
+ (responseCode, tokenInfo) = success ? abi.decode(result, (int32, IHederaTokenService.TokenInfo)) : (HederaResponseCodes.UNKNOWN, defaultTokenInfo);
+ }
+
+ /// Retrieves non-fungible specific token info for a given NFT
+ /// @param token The ID of the token as a solidity address
+ function getNonFungibleTokenInfo(address token, int64 serialNumber) internal returns (int responseCode, IHederaTokenService.NonFungibleTokenInfo memory tokenInfo) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getNonFungibleTokenInfo.selector, token, serialNumber));
+ IHederaTokenService.NonFungibleTokenInfo memory defaultTokenInfo;
+ (responseCode, tokenInfo) = success ? abi.decode(result, (int32, IHederaTokenService.NonFungibleTokenInfo)) : (HederaResponseCodes.UNKNOWN, defaultTokenInfo);
+ }
+
+ /// Query token custom fees
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return fixedFees Set of fixed fees for `token`
+ /// @return fractionalFees Set of fractional fees for `token`
+ /// @return royaltyFees Set of royalty fees for `token`
+ function getTokenCustomFees(address token) internal returns (int64 responseCode,
+ IHederaTokenService.FixedFee[] memory fixedFees,
+ IHederaTokenService.FractionalFee[] memory fractionalFees,
+ IHederaTokenService.RoyaltyFee[] memory royaltyFees) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenCustomFees.selector, token));
+ IHederaTokenService.FixedFee[] memory defaultFixedFees;
+ IHederaTokenService.FractionalFee[] memory defaultFractionalFees;
+ IHederaTokenService.RoyaltyFee[] memory defaultRoyaltyFees;
+ (responseCode, fixedFees, fractionalFees, royaltyFees) =
+ success ? abi.decode
+ (result, (int32, IHederaTokenService.FixedFee[], IHederaTokenService.FractionalFee[], IHederaTokenService.RoyaltyFee[]))
+ : (HederaResponseCodes.UNKNOWN, defaultFixedFees, defaultFractionalFees, defaultRoyaltyFees);
+ }
+
+ /// Allows spender to withdraw from your account multiple times, up to the value amount. If this function is called
+ /// again it overwrites the current allowance with value.
+ /// Only Applicable to Fungible Tokens
+ /// @param token The hedera token address to approve
+ /// @param spender the account authorized to spend
+ /// @param amount the amount of tokens authorized to spend.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function approve(address token, address spender, uint256 amount) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.approve.selector,
+ token, spender, amount));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Allows spender to withdraw from your account multiple times, up to the value amount. If this function is called
+ /// again it overwrites the current allowance with value.
+ /// Only Applicable to Fungible Tokens
+ /// @param token The hedera token address to approve
+ /// @param spender the account authorized to spend
+ /// @param amount the amount of tokens authorized to spend.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function delegateApprove(address token, address spender, uint256 amount) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.delegatecall(
+ abi.encodeWithSelector(IHederaTokenService.approve.selector,
+ token, spender, amount));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Transfers `amount` tokens from `from` to `to` using the
+ // allowance mechanism. `amount` is then deducted from the caller's allowance.
+ /// Only applicable to fungible tokens
+ /// @param token The address of the fungible Hedera token to transfer
+ /// @param from The account address of the owner of the token, on the behalf of which to transfer `amount` tokens
+ /// @param to The account address of the receiver of the `amount` tokens
+ /// @param amount The amount of tokens to transfer from `from` to `to`
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function transferFrom(address token, address from, address to, uint256 amount) external returns (int64 responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.transferFrom.selector,
+ token, from, to, amount));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Transfers `amount` tokens from `from` to `to` using the
+ // allowance mechanism. `amount` is then deducted from the caller's allowance.
+ /// Only applicable to fungible tokens
+ /// @param token The address of the fungible Hedera token to transfer
+ /// @param from The account address of the owner of the token, on the behalf of which to transfer `amount` tokens
+ /// @param to The account address of the receiver of the `amount` tokens
+ /// @param amount The amount of tokens to transfer from `from` to `to`
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function delegateTransferFrom(address token, address from, address to, uint256 amount) external returns (int64 responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.delegatecall(
+ abi.encodeWithSelector(IHederaTokenService.transferFrom.selector,
+ token, from, to, amount));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Transfers `serialNumber` of `token` from `from` to `to` using the allowance mechanism.
+ /// Only applicable to NFT tokens
+ /// @param token The address of the non-fungible Hedera token to transfer
+ /// @param from The account address of the owner of `serialNumber` of `token`
+ /// @param to The account address of the receiver of `serialNumber`
+ /// @param serialNumber The NFT serial number to transfer
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function transferFromNFT(address token, address from, address to, uint256 serialNumber) external returns (int64 responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.transferFromNFT.selector,
+ token, from, to, serialNumber));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Transfers `serialNumber` of `token` from `from` to `to` using the allowance mechanism.
+ /// Only applicable to NFT tokens
+ /// @param token The address of the non-fungible Hedera token to transfer
+ /// @param from The account address of the owner of `serialNumber` of `token`
+ /// @param to The account address of the receiver of `serialNumber`
+ /// @param serialNumber The NFT serial number to transfer
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function delegateTransferFromNFT(address token, address from, address to, uint256 serialNumber) external returns (int64 responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.delegatecall(
+ abi.encodeWithSelector(IHederaTokenService.transferFromNFT.selector,
+ token, from, to, serialNumber));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Returns the amount which spender is still allowed to withdraw from owner.
+ /// Only Applicable to Fungible Tokens
+ /// @param token The Hedera token address to check the allowance of
+ /// @param owner the owner of the tokens to be spent
+ /// @param spender the spender of the tokens
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function allowance(address token, address owner, address spender) internal returns (int responseCode, uint256 amount)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.allowance.selector,
+ token, owner, spender));
+ (responseCode, amount) = success ? abi.decode(result, (int32, uint256)) : (HederaResponseCodes.UNKNOWN, 0);
+ }
+
+ /// Allow or reaffirm the approved address to transfer an NFT the approved address does not own.
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to approve
+ /// @param approved The new approved NFT controller. To revoke approvals pass in the zero address.
+ /// @param serialNumber The NFT serial number to approve
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function approveNFT(address token, address approved, uint256 serialNumber) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.approveNFT.selector,
+ token, approved, serialNumber));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Allow or reaffirm the approved address to transfer an NFT the approved address does not own.
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to approve
+ /// @param approved The new approved NFT controller. To revoke approvals pass in the zero address.
+ /// @param serialNumber The NFT serial number to approve
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function delegateApproveNFT(address token, address approved, uint256 serialNumber) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.delegatecall(
+ abi.encodeWithSelector(IHederaTokenService.approveNFT.selector,
+ token, approved, serialNumber));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Get the approved address for a single NFT
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to check approval
+ /// @param serialNumber The NFT to find the approved address for
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return approved The approved address for this NFT, or the zero address if there is none
+ function getApproved(address token, uint256 serialNumber) internal returns (int responseCode, address approved)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getApproved.selector,
+ token, serialNumber));
+ (responseCode, approved) =
+ success
+ ? abi.decode(result, (int32, address))
+ : (HederaResponseCodes.UNKNOWN, address(0));
+ }
+
+ /// Query if token account is frozen
+ /// @param token The token address to check
+ /// @param account The account address associated with the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return frozen True if `account` is frozen for `token`
+ function isFrozen(address token, address account) internal returns (int64 responseCode, bool frozen){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.isFrozen.selector, token, account));
+ (responseCode, frozen) = success ? abi.decode(result, (int32, bool)) : (HederaResponseCodes.UNKNOWN, false);
+ }
+
+ /// Query if token account has kyc granted
+ /// @param token The token address to check
+ /// @param account The account address associated with the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return kycGranted True if `account` has kyc granted for `token`
+ function isKyc(address token, address account) internal returns (int64 responseCode, bool kycGranted){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.isKyc.selector, token, account));
+ (responseCode, kycGranted) = success ? abi.decode(result, (int32, bool)) : (HederaResponseCodes.UNKNOWN, false);
+ }
+
+ /// Operation to freeze token account
+ /// @param token The token address
+ /// @param account The account address to be frozen
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function freezeToken(address token, address account) internal returns (int64 responseCode){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.freezeToken.selector, token, account));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to unfreeze token account
+ /// @param token The token address
+ /// @param account The account address to be unfrozen
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function unfreezeToken(address token, address account) internal returns (int64 responseCode){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.unfreezeToken.selector, token, account));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to grant kyc to token account
+ /// @param token The token address
+ /// @param account The account address to grant kyc
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function grantTokenKyc(address token, address account) internal returns (int64 responseCode){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.grantTokenKyc.selector, token, account));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to revoke kyc to token account
+ /// @param token The token address
+ /// @param account The account address to revoke kyc
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function revokeTokenKyc(address token, address account) internal returns (int64 responseCode){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.revokeTokenKyc.selector, token, account));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Enable or disable approval for a third party ("operator") to manage
+ /// all of `msg.sender`'s assets
+ /// @param token The Hedera NFT token address to approve
+ /// @param operator Address to add to the set of authorized operators
+ /// @param approved True if the operator is approved, false to revoke approval
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function setApprovalForAll(address token, address operator, bool approved) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.setApprovalForAll.selector,
+ token, operator, approved));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Enable or disable approval for a third party ("operator") to manage
+ /// all of `msg.sender`'s assets
+ /// @param token The Hedera NFT token address to approve
+ /// @param operator Address to add to the set of authorized operators
+ /// @param approved True if the operator is approved, false to revoke approval
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function delegateSetApprovalForAll(address token, address operator, bool approved) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.delegatecall(
+ abi.encodeWithSelector(IHederaTokenService.setApprovalForAll.selector,
+ token, operator, approved));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Query if an address is an authorized operator for another address
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to approve
+ /// @param owner The address that owns the NFTs
+ /// @param operator The address that acts on behalf of the owner
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return approved True if `operator` is an approved operator for `owner`, false otherwise
+ function isApprovedForAll(address token, address owner, address operator) internal returns (int responseCode, bool approved)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.isApprovedForAll.selector,
+ token, owner, operator));
+ (responseCode, approved) =
+ success
+ ? abi.decode(result, (int32, bool))
+ : (HederaResponseCodes.UNKNOWN, false);
+ }
+
+ /// Query token default freeze status
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return defaultFreezeStatus True if `token` default freeze status is frozen.
+ function getTokenDefaultFreezeStatus(address token) internal returns (int responseCode, bool defaultFreezeStatus) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenDefaultFreezeStatus.selector, token));
+ (responseCode, defaultFreezeStatus) = success ? abi.decode(result, (int32, bool)) : (HederaResponseCodes.UNKNOWN, false);
+ }
+
+ /// Query token default kyc status
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return defaultKycStatus True if `token` default kyc status is KycNotApplicable and false if Revoked.
+ function getTokenDefaultKycStatus(address token) internal returns (int responseCode, bool defaultKycStatus) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenDefaultKycStatus.selector, token));
+ (responseCode, defaultKycStatus) = success ? abi.decode(result, (int32, bool)) : (HederaResponseCodes.UNKNOWN, false);
+ }
+
+ /**********************
+ * ABI v1 calls *
+ **********************/
+
+ /// Initiates a Fungible Token Transfer
+ /// @param token The ID of the token as a solidity address
+ /// @param accountIds account to do a transfer to/from
+ /// @param amounts The amount from the accountId at the same index
+ function transferTokens(address token, address[] memory accountIds, int64[] memory amounts) internal
+ returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.transferTokens.selector,
+ token, accountIds, amounts));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Initiates a Non-Fungable Token Transfer
+ /// @param token The ID of the token as a solidity address
+ /// @param sender the sender of an nft
+ /// @param receiver the receiver of the nft sent by the same index at sender
+ /// @param serialNumber the serial number of the nft sent by the same index at sender
+ function transferNFTs(address token, address[] memory sender, address[] memory receiver, int64[] memory serialNumber)
+ internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.transferNFTs.selector,
+ token, sender, receiver, serialNumber));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Transfers tokens where the calling account/contract is implicitly the first entry in the token transfer list,
+ /// where the amount is the value needed to zero balance the transfers. Regular signing rules apply for sending
+ /// (positive amount) or receiving (negative amount)
+ /// @param token The token to transfer to/from
+ /// @param sender The sender for the transaction
+ /// @param receiver The receiver of the transaction
+ /// @param amount Non-negative value to send. a negative value will result in a failure.
+ function transferToken(address token, address sender, address receiver, int64 amount) internal
+ returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.transferToken.selector,
+ token, sender, receiver, amount));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Transfers tokens where the calling account/contract is implicitly the first entry in the token transfer list,
+ /// where the amount is the value needed to zero balance the transfers. Regular signing rules apply for sending
+ /// (positive amount) or receiving (negative amount)
+ /// @param token The token to transfer to/from
+ /// @param sender The sender for the transaction
+ /// @param receiver The receiver of the transaction
+ /// @param serialNumber The serial number of the NFT to transfer.
+ function transferNFT(address token, address sender, address receiver, int64 serialNumber) internal
+ returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.transferNFT.selector,
+ token, sender, receiver, serialNumber));
+ responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to pause token
+ /// @param token The token address to be paused
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function pauseToken(address token) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.pauseToken.selector, token));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to unpause token
+ /// @param token The token address to be unpaused
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function unpauseToken(address token) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.unpauseToken.selector, token));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to wipe fungible tokens from account
+ /// @param token The token address
+ /// @param account The account address to revoke kyc
+ /// @param amount The number of tokens to wipe
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function wipeTokenAccount(address token, address account, int64 amount) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.wipeTokenAccount.selector, token, account, amount));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to wipe non fungible tokens from account
+ /// @param token The token address
+ /// @param account The account address to revoke kyc
+ /// @param serialNumbers The serial numbers of token to wipe
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function wipeTokenAccountNFT(address token, address account, int64[] memory serialNumbers) internal
+ returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.wipeTokenAccountNFT.selector, token, account, serialNumbers));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to delete token
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function deleteToken(address token) internal returns (int responseCode)
+ {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.deleteToken.selector, token));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to update token expiry info
+ /// @param token The token address
+ /// @param keys The token keys
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function updateTokenKeys(address token, IHederaTokenService.TokenKey[] memory keys)
+ internal returns (int64 responseCode){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.updateTokenKeys.selector, token, keys));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Query token KeyValue
+ /// @param token The token address to check
+ /// @param keyType The keyType of the desired KeyValue
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return key KeyValue info for key of type `keyType`
+ function getTokenKey(address token, uint keyType)
+ internal returns (int64 responseCode, IHederaTokenService.KeyValue memory key){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenKey.selector, token, keyType));
+ IHederaTokenService.KeyValue memory defaultKeyValueInfo;
+ (responseCode, key) = success ? abi.decode(result, (int32,IHederaTokenService.KeyValue) ) : (HederaResponseCodes.UNKNOWN, defaultKeyValueInfo);
+ }
+
+
+ /// Query if valid token found for the given address
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return isTokenFlag True if valid token found for the given address
+ function isToken(address token) internal returns (int64 responseCode, bool isTokenFlag) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.isToken.selector, token));
+ (responseCode, isTokenFlag) = success ? abi.decode(result, (int32, bool)) : (HederaResponseCodes.UNKNOWN, false);
+ }
+
+ /// Query to return the token type for a given address
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenType the token type. 0 is FUNGIBLE_COMMON, 1 is NON_FUNGIBLE_UNIQUE, -1 is UNRECOGNIZED
+ function getTokenType(address token) internal returns (int64 responseCode, int32 tokenType) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenType.selector, token));
+ (responseCode, tokenType) = success ? abi.decode(result, (int32, int32)) : (HederaResponseCodes.UNKNOWN, - 1);
+ }
+
+ /// Operation to get token expiry info
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return expiryInfo The expiry info of the token
+ function getTokenExpiryInfo(address token) internal returns (int responseCode, IHederaTokenService.Expiry memory expiryInfo){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.getTokenExpiryInfo.selector, token));
+ IHederaTokenService.Expiry memory defaultExpiryInfo;
+ (responseCode, expiryInfo) = success ? abi.decode(result, (int32, IHederaTokenService.Expiry)) : (HederaResponseCodes.UNKNOWN, defaultExpiryInfo);
+ }
+
+ /// Operation to update token expiry info
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function updateTokenExpiryInfo(address token, IHederaTokenService.Expiry memory expiryInfo) internal returns (int responseCode){
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.updateTokenExpiryInfo.selector, token, expiryInfo));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+
+ /// Operation to update token info
+ /// @param token The token address
+ /// @param tokenInfo The hedera token info to update token with
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function updateTokenInfo(address token, IHederaTokenService.HederaToken memory tokenInfo) internal returns (int responseCode) {
+ (bool success, bytes memory result) = precompileAddress.call(
+ abi.encodeWithSelector(IHederaTokenService.updateTokenInfo.selector, token, tokenInfo));
+ (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
+ }
+}
diff --git a/tests/unit/utils/solc/hts/IHederaTokenService.sol b/tests/unit/utils/solc/hts/IHederaTokenService.sol
new file mode 100644
index 000000000..294613662
--- /dev/null
+++ b/tests/unit/utils/solc/hts/IHederaTokenService.sol
@@ -0,0 +1,797 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity >=0.4.9 <0.9.0;
+pragma experimental ABIEncoderV2;
+
+interface IHederaTokenService {
+
+ /// Transfers cryptocurrency among two or more accounts by making the desired adjustments to their
+ /// balances. Each transfer list can specify up to 10 adjustments. Each negative amount is withdrawn
+ /// from the corresponding account (a sender), and each positive one is added to the corresponding
+ /// account (a receiver). The amounts list must sum to zero. Each amount is a number of tinybars
+ /// (there are 100,000,000 tinybars in one hbar). If any sender account fails to have sufficient
+ /// hbars, then the entire transaction fails, and none of those transfers occur, though the
+ /// transaction fee is still charged. This transaction must be signed by the keys for all the sending
+ /// accounts, and for any receiving accounts that have receiverSigRequired == true. The signatures
+ /// are in the same order as the accounts, skipping those accounts that don't need a signature.
+ /// @custom:version 0.3.0 previous version did not include isApproval
+ struct AccountAmount {
+ // The Account ID, as a solidity address, that sends/receives cryptocurrency or tokens
+ address accountID;
+
+ // The amount of the lowest denomination of the given token that
+ // the account sends(negative) or receives(positive)
+ int64 amount;
+
+ // If true then the transfer is expected to be an approved allowance and the
+ // accountID is expected to be the owner. The default is false (omitted).
+ bool isApproval;
+ }
+
+ /// A sender account, a receiver account, and the serial number of an NFT of a Token with
+ /// NON_FUNGIBLE_UNIQUE type. When minting NFTs the sender will be the default AccountID instance
+ /// (0.0.0 aka 0x0) and when burning NFTs, the receiver will be the default AccountID instance.
+ /// @custom:version 0.3.0 previous version did not include isApproval
+ struct NftTransfer {
+ // The solidity address of the sender
+ address senderAccountID;
+
+ // The solidity address of the receiver
+ address receiverAccountID;
+
+ // The serial number of the NFT
+ int64 serialNumber;
+
+ // If true then the transfer is expected to be an approved allowance and the
+ // accountID is expected to be the owner. The default is false (omitted).
+ bool isApproval;
+ }
+
+ struct TokenTransferList {
+ // The ID of the token as a solidity address
+ address token;
+
+ // Applicable to tokens of type FUNGIBLE_COMMON. Multiple list of AccountAmounts, each of which
+ // has an account and amount.
+ AccountAmount[] transfers;
+
+ // Applicable to tokens of type NON_FUNGIBLE_UNIQUE. Multiple list of NftTransfers, each of
+ // which has a sender and receiver account, including the serial number of the NFT
+ NftTransfer[] nftTransfers;
+ }
+
+ struct TransferList {
+ // Multiple list of AccountAmounts, each of which has an account and amount.
+ // Used to transfer hbars between the accounts in the list.
+ AccountAmount[] transfers;
+ }
+
+ /// Expiry properties of a Hedera token - second, autoRenewAccount, autoRenewPeriod
+ struct Expiry {
+ // The epoch second at which the token should expire; if an auto-renew account and period are
+ // specified, this is coerced to the current epoch second plus the autoRenewPeriod
+ int64 second;
+
+ // ID of an account which will be automatically charged to renew the token's expiration, at
+ // autoRenewPeriod interval, expressed as a solidity address
+ address autoRenewAccount;
+
+ // The interval at which the auto-renew account will be charged to extend the token's expiry
+ int64 autoRenewPeriod;
+ }
+
+ /// A Key can be a public key from either the Ed25519 or ECDSA(secp256k1) signature schemes, where
+ /// in the ECDSA(secp256k1) case we require the 33-byte compressed form of the public key. We call
+ /// these public keys primitive keys .
+ /// A Key can also be the ID of a smart contract instance, which is then authorized to perform any
+ /// precompiled contract action that requires this key to sign.
+ /// Note that when a Key is a smart contract ID, it doesn't mean the contract with that ID
+ /// will actually create a cryptographic signature. It only means that when the contract calls a
+ /// precompiled contract, the resulting "child transaction" will be authorized to perform any action
+ /// controlled by the Key.
+ /// Exactly one of the possible values should be populated in order for the Key to be valid.
+ struct KeyValue {
+
+ // if set to true, the key of the calling Hedera account will be inherited as the token key
+ bool inheritAccountKey;
+
+ // smart contract instance that is authorized as if it had signed with a key
+ address contractId;
+
+ // Ed25519 public key bytes
+ bytes ed25519;
+
+ // Compressed ECDSA(secp256k1) public key bytes
+ bytes ECDSA_secp256k1;
+
+ // A smart contract that, if the recipient of the active message frame, should be treated
+ // as having signed. (Note this does not mean the code being executed in the frame
+ // will belong to the given contract, since it could be running another contract's code via
+ // delegatecall . So setting this key is a more permissive version of setting the
+ // contractID key, which also requires the code in the active message frame belong to the
+ // the contract with the given id.)
+ address delegatableContractId;
+ }
+
+ /// A list of token key types the key should be applied to and the value of the key
+ struct TokenKey {
+
+ // bit field representing the key type. Keys of all types that have corresponding bits set to 1
+ // will be created for the token.
+ // 0th bit: adminKey
+ // 1st bit: kycKey
+ // 2nd bit: freezeKey
+ // 3rd bit: wipeKey
+ // 4th bit: supplyKey
+ // 5th bit: feeScheduleKey
+ // 6th bit: pauseKey
+ // 7th bit: ignored
+ uint keyType;
+
+ // the value that will be set to the key type
+ KeyValue key;
+ }
+
+ /// Basic properties of a Hedera Token - name, symbol, memo, tokenSupplyType, maxSupply,
+ /// treasury, freezeDefault. These properties are related both to Fungible and NFT token types.
+ struct HederaToken {
+ // The publicly visible name of the token. The token name is specified as a Unicode string.
+ // Its UTF-8 encoding cannot exceed 100 bytes, and cannot contain the 0 byte (NUL).
+ string name;
+
+ // The publicly visible token symbol. The token symbol is specified as a Unicode string.
+ // Its UTF-8 encoding cannot exceed 100 bytes, and cannot contain the 0 byte (NUL).
+ string symbol;
+
+ // The ID of the account which will act as a treasury for the token as a solidity address.
+ // This account will receive the specified initial supply or the newly minted NFTs in
+ // the case for NON_FUNGIBLE_UNIQUE Type
+ address treasury;
+
+ // The memo associated with the token (UTF-8 encoding max 100 bytes)
+ string memo;
+
+ // IWA compatibility. Specified the token supply type. Defaults to INFINITE
+ bool tokenSupplyType;
+
+ // IWA Compatibility. Depends on TokenSupplyType. For tokens of type FUNGIBLE_COMMON - the
+ // maximum number of tokens that can be in circulation. For tokens of type NON_FUNGIBLE_UNIQUE -
+ // the maximum number of NFTs (serial numbers) that can be minted. This field can never be changed!
+ int64 maxSupply;
+
+ // The default Freeze status (frozen or unfrozen) of Hedera accounts relative to this token. If
+ // true, an account must be unfrozen before it can receive the token
+ bool freezeDefault;
+
+ // list of keys to set to the token
+ TokenKey[] tokenKeys;
+
+ // expiry properties of a Hedera token - second, autoRenewAccount, autoRenewPeriod
+ Expiry expiry;
+ }
+
+ /// Additional post creation fungible and non fungible properties of a Hedera Token.
+ struct TokenInfo {
+ /// Basic properties of a Hedera Token
+ HederaToken token;
+
+ /// The number of tokens (fungible) or serials (non-fungible) of the token
+ int64 totalSupply;
+
+ /// Specifies whether the token is deleted or not
+ bool deleted;
+
+ /// Specifies whether the token kyc was defaulted with KycNotApplicable (true) or Revoked (false)
+ bool defaultKycStatus;
+
+ /// Specifies whether the token is currently paused or not
+ bool pauseStatus;
+
+ /// The fixed fees collected when transferring the token
+ FixedFee[] fixedFees;
+
+ /// The fractional fees collected when transferring the token
+ FractionalFee[] fractionalFees;
+
+ /// The royalty fees collected when transferring the token
+ RoyaltyFee[] royaltyFees;
+
+ /// The ID of the network ledger
+ string ledgerId;
+ }
+
+ /// Additional fungible properties of a Hedera Token.
+ struct FungibleTokenInfo {
+ /// The shared hedera token info
+ TokenInfo tokenInfo;
+
+ /// The number of decimal places a token is divisible by
+ int32 decimals;
+ }
+
+ /// Additional non fungible properties of a Hedera Token.
+ struct NonFungibleTokenInfo {
+ /// The shared hedera token info
+ TokenInfo tokenInfo;
+
+ /// The serial number of the nft
+ int64 serialNumber;
+
+ /// The account id specifying the owner of the non fungible token
+ address ownerId;
+
+ /// The epoch second at which the token was created.
+ int64 creationTime;
+
+ /// The unique metadata of the NFT
+ bytes metadata;
+
+ /// The account id specifying an account that has been granted spending permissions on this nft
+ address spenderId;
+ }
+
+ /// A fixed number of units (hbar or token) to assess as a fee during a transfer of
+ /// units of the token to which this fixed fee is attached. The denomination of
+ /// the fee depends on the values of tokenId, useHbarsForPayment and
+ /// useCurrentTokenForPayment. Exactly one of the values should be set.
+ struct FixedFee {
+
+ int64 amount;
+
+ // Specifies ID of token that should be used for fixed fee denomination
+ address tokenId;
+
+ // Specifies this fixed fee should be denominated in Hbar
+ bool useHbarsForPayment;
+
+ // Specifies this fixed fee should be denominated in the Token currently being created
+ bool useCurrentTokenForPayment;
+
+ // The ID of the account to receive the custom fee, expressed as a solidity address
+ address feeCollector;
+ }
+
+ /// A fraction of the transferred units of a token to assess as a fee. The amount assessed will never
+ /// be less than the given minimumAmount, and never greater than the given maximumAmount. The
+ /// denomination is always units of the token to which this fractional fee is attached.
+ struct FractionalFee {
+ // A rational number's numerator, used to set the amount of a value transfer to collect as a custom fee
+ int64 numerator;
+
+ // A rational number's denominator, used to set the amount of a value transfer to collect as a custom fee
+ int64 denominator;
+
+ // The minimum amount to assess
+ int64 minimumAmount;
+
+ // The maximum amount to assess (zero implies no maximum)
+ int64 maximumAmount;
+ bool netOfTransfers;
+
+ // The ID of the account to receive the custom fee, expressed as a solidity address
+ address feeCollector;
+ }
+
+ /// A fee to assess during a transfer that changes ownership of an NFT. Defines the fraction of
+ /// the fungible value exchanged for an NFT that the ledger should collect as a royalty. ("Fungible
+ /// value" includes both ℏ and units of fungible HTS tokens.) When the NFT sender does not receive
+ /// any fungible value, the ledger will assess the fallback fee, if present, to the new NFT owner.
+ /// Royalty fees can only be added to tokens of type type NON_FUNGIBLE_UNIQUE.
+ struct RoyaltyFee {
+ // A fraction's numerator of fungible value exchanged for an NFT to collect as royalty
+ int64 numerator;
+
+ // A fraction's denominator of fungible value exchanged for an NFT to collect as royalty
+ int64 denominator;
+
+ // If present, the fee to assess to the NFT receiver when no fungible value
+ // is exchanged with the sender. Consists of:
+ // amount: the amount to charge for the fee
+ // tokenId: Specifies ID of token that should be used for fixed fee denomination
+ // useHbarsForPayment: Specifies this fee should be denominated in Hbar
+ int64 amount;
+ address tokenId;
+ bool useHbarsForPayment;
+
+ // The ID of the account to receive the custom fee, expressed as a solidity address
+ address feeCollector;
+ }
+
+ /**********************
+ * Direct HTS Calls *
+ **********************/
+
+ /// Performs transfers among combinations of tokens and hbars
+ /// @param transferList the list of hbar transfers to do
+ /// @param tokenTransfers the list of token transfers to do
+ /// @custom:version 0.3.0 the signature of the previous version was cryptoTransfer(TokenTransferList[] memory tokenTransfers)
+ function cryptoTransfer(TransferList memory transferList, TokenTransferList[] memory tokenTransfers)
+ external
+ returns (int64 responseCode);
+
+ /// Mints an amount of the token to the defined treasury account
+ /// @param token The token for which to mint tokens. If token does not exist, transaction results in
+ /// INVALID_TOKEN_ID
+ /// @param amount Applicable to tokens of type FUNGIBLE_COMMON. The amount to mint to the Treasury Account.
+ /// Amount must be a positive non-zero number represented in the lowest denomination of the
+ /// token. The new supply must be lower than 2^63.
+ /// @param metadata Applicable to tokens of type NON_FUNGIBLE_UNIQUE. A list of metadata that are being created.
+ /// Maximum allowed size of each metadata is 100 bytes
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return newTotalSupply The new supply of tokens. For NFTs it is the total count of NFTs
+ /// @return serialNumbers If the token is an NFT the newly generate serial numbers, othersise empty.
+ function mintToken(
+ address token,
+ int64 amount,
+ bytes[] memory metadata
+ )
+ external
+ returns (
+ int64 responseCode,
+ int64 newTotalSupply,
+ int64[] memory serialNumbers
+ );
+
+ /// Burns an amount of the token from the defined treasury account
+ /// @param token The token for which to burn tokens. If token does not exist, transaction results in
+ /// INVALID_TOKEN_ID
+ /// @param amount Applicable to tokens of type FUNGIBLE_COMMON. The amount to burn from the Treasury Account.
+ /// Amount must be a positive non-zero number, not bigger than the token balance of the treasury
+ /// account (0; balance], represented in the lowest denomination.
+ /// @param serialNumbers Applicable to tokens of type NON_FUNGIBLE_UNIQUE. The list of serial numbers to be burned.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return newTotalSupply The new supply of tokens. For NFTs it is the total count of NFTs
+ function burnToken(
+ address token,
+ int64 amount,
+ int64[] memory serialNumbers
+ ) external returns (int64 responseCode, int64 newTotalSupply);
+
+ /// Associates the provided account with the provided tokens. Must be signed by the provided
+ /// Account's key or called from the accounts contract key
+ /// If the provided account is not found, the transaction will resolve to INVALID_ACCOUNT_ID.
+ /// If the provided account has been deleted, the transaction will resolve to ACCOUNT_DELETED.
+ /// If any of the provided tokens is not found, the transaction will resolve to INVALID_TOKEN_REF.
+ /// If any of the provided tokens has been deleted, the transaction will resolve to TOKEN_WAS_DELETED.
+ /// If an association between the provided account and any of the tokens already exists, the
+ /// transaction will resolve to TOKEN_ALREADY_ASSOCIATED_TO_ACCOUNT.
+ /// If the provided account's associations count exceed the constraint of maximum token associations
+ /// per account, the transaction will resolve to TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED.
+ /// On success, associations between the provided account and tokens are made and the account is
+ /// ready to interact with the tokens.
+ /// @param account The account to be associated with the provided tokens
+ /// @param tokens The tokens to be associated with the provided account. In the case of NON_FUNGIBLE_UNIQUE
+ /// Type, once an account is associated, it can hold any number of NFTs (serial numbers) of that
+ /// token type
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function associateTokens(address account, address[] memory tokens)
+ external
+ returns (int64 responseCode);
+
+ /// Single-token variant of associateTokens. Will be mapped to a single entry array call of associateTokens
+ /// @param account The account to be associated with the provided token
+ /// @param token The token to be associated with the provided account
+ function associateToken(address account, address token)
+ external
+ returns (int64 responseCode);
+
+ /// Dissociates the provided account with the provided tokens. Must be signed by the provided
+ /// Account's key.
+ /// If the provided account is not found, the transaction will resolve to INVALID_ACCOUNT_ID.
+ /// If the provided account has been deleted, the transaction will resolve to ACCOUNT_DELETED.
+ /// If any of the provided tokens is not found, the transaction will resolve to INVALID_TOKEN_REF.
+ /// If any of the provided tokens has been deleted, the transaction will resolve to TOKEN_WAS_DELETED.
+ /// If an association between the provided account and any of the tokens does not exist, the
+ /// transaction will resolve to TOKEN_NOT_ASSOCIATED_TO_ACCOUNT.
+ /// If a token has not been deleted and has not expired, and the user has a nonzero balance, the
+ /// transaction will resolve to TRANSACTION_REQUIRES_ZERO_TOKEN_BALANCES.
+ /// If a fungible token has expired, the user can disassociate even if their token balance is
+ /// not zero.
+ /// If a non fungible token has expired, the user can not disassociate if their token
+ /// balance is not zero. The transaction will resolve to TRANSACTION_REQUIRED_ZERO_TOKEN_BALANCES.
+ /// On success, associations between the provided account and tokens are removed.
+ /// @param account The account to be dissociated from the provided tokens
+ /// @param tokens The tokens to be dissociated from the provided account.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function dissociateTokens(address account, address[] memory tokens)
+ external
+ returns (int64 responseCode);
+
+ /// Single-token variant of dissociateTokens. Will be mapped to a single entry array call of dissociateTokens
+ /// @param account The account to be associated with the provided token
+ /// @param token The token to be associated with the provided account
+ function dissociateToken(address account, address token)
+ external
+ returns (int64 responseCode);
+
+ /// Creates a Fungible Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @param initialTotalSupply Specifies the initial supply of tokens to be put in circulation. The
+ /// initial supply is sent to the Treasury Account. The supply is in the lowest denomination possible.
+ /// @param decimals the number of decimal places a token is divisible by
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createFungibleToken(
+ HederaToken memory token,
+ int64 initialTotalSupply,
+ int32 decimals
+ ) external payable returns (int64 responseCode, address tokenAddress);
+
+ /// Creates a Fungible Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @param initialTotalSupply Specifies the initial supply of tokens to be put in circulation. The
+ /// initial supply is sent to the Treasury Account. The supply is in the lowest denomination possible.
+ /// @param decimals the number of decimal places a token is divisible by.
+ /// @param fixedFees list of fixed fees to apply to the token
+ /// @param fractionalFees list of fractional fees to apply to the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createFungibleTokenWithCustomFees(
+ HederaToken memory token,
+ int64 initialTotalSupply,
+ int32 decimals,
+ FixedFee[] memory fixedFees,
+ FractionalFee[] memory fractionalFees
+ ) external payable returns (int64 responseCode, address tokenAddress);
+
+ /// Creates an Non Fungible Unique Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createNonFungibleToken(HederaToken memory token)
+ external
+ payable
+ returns (int64 responseCode, address tokenAddress);
+
+ /// Creates an Non Fungible Unique Token with the specified properties
+ /// @param token the basic properties of the token being created
+ /// @param fixedFees list of fixed fees to apply to the token
+ /// @param royaltyFees list of royalty fees to apply to the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenAddress the created token's address
+ function createNonFungibleTokenWithCustomFees(
+ HederaToken memory token,
+ FixedFee[] memory fixedFees,
+ RoyaltyFee[] memory royaltyFees
+ ) external payable returns (int64 responseCode, address tokenAddress);
+
+ /**********************
+ * ABIV1 calls *
+ **********************/
+
+ /// Initiates a Fungible Token Transfer
+ /// @param token The ID of the token as a solidity address
+ /// @param accountId account to do a transfer to/from
+ /// @param amount The amount from the accountId at the same index
+ function transferTokens(
+ address token,
+ address[] memory accountId,
+ int64[] memory amount
+ ) external returns (int64 responseCode);
+
+ /// Initiates a Non-Fungable Token Transfer
+ /// @param token The ID of the token as a solidity address
+ /// @param sender the sender of an nft
+ /// @param receiver the receiver of the nft sent by the same index at sender
+ /// @param serialNumber the serial number of the nft sent by the same index at sender
+ function transferNFTs(
+ address token,
+ address[] memory sender,
+ address[] memory receiver,
+ int64[] memory serialNumber
+ ) external returns (int64 responseCode);
+
+ /// Transfers tokens where the calling account/contract is implicitly the first entry in the token transfer list,
+ /// where the amount is the value needed to zero balance the transfers. Regular signing rules apply for sending
+ /// (positive amount) or receiving (negative amount)
+ /// @param token The token to transfer to/from
+ /// @param sender The sender for the transaction
+ /// @param recipient The receiver of the transaction
+ /// @param amount Non-negative value to send. a negative value will result in a failure.
+ function transferToken(
+ address token,
+ address sender,
+ address recipient,
+ int64 amount
+ ) external returns (int64 responseCode);
+
+ /// Transfers tokens where the calling account/contract is implicitly the first entry in the token transfer list,
+ /// where the amount is the value needed to zero balance the transfers. Regular signing rules apply for sending
+ /// (positive amount) or receiving (negative amount)
+ /// @param token The token to transfer to/from
+ /// @param sender The sender for the transaction
+ /// @param recipient The receiver of the transaction
+ /// @param serialNumber The serial number of the NFT to transfer.
+ function transferNFT(
+ address token,
+ address sender,
+ address recipient,
+ int64 serialNumber
+ ) external returns (int64 responseCode);
+
+ /// Allows spender to withdraw from your account multiple times, up to the value amount. If this function is called
+ /// again it overwrites the current allowance with value.
+ /// Only Applicable to Fungible Tokens
+ /// @param token The hedera token address to approve
+ /// @param spender the account address authorized to spend
+ /// @param amount the amount of tokens authorized to spend.
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function approve(
+ address token,
+ address spender,
+ uint256 amount
+ ) external returns (int64 responseCode);
+
+ /// Transfers `amount` tokens from `from` to `to` using the
+ // allowance mechanism. `amount` is then deducted from the caller's allowance.
+ /// Only applicable to fungible tokens
+ /// @param token The address of the fungible Hedera token to transfer
+ /// @param from The account address of the owner of the token, on the behalf of which to transfer `amount` tokens
+ /// @param to The account address of the receiver of the `amount` tokens
+ /// @param amount The amount of tokens to transfer from `from` to `to`
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function transferFrom(address token, address from, address to, uint256 amount) external returns (int64 responseCode);
+
+ /// Returns the amount which spender is still allowed to withdraw from owner.
+ /// Only Applicable to Fungible Tokens
+ /// @param token The Hedera token address to check the allowance of
+ /// @param owner the owner of the tokens to be spent
+ /// @param spender the spender of the tokens
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return allowance The amount which spender is still allowed to withdraw from owner.
+ function allowance(
+ address token,
+ address owner,
+ address spender
+ ) external returns (int64 responseCode, uint256 allowance);
+
+ /// Allow or reaffirm the approved address to transfer an NFT the approved address does not own.
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to approve
+ /// @param approved The new approved NFT controller. To revoke approvals pass in the zero address.
+ /// @param serialNumber The NFT serial number to approve
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function approveNFT(
+ address token,
+ address approved,
+ uint256 serialNumber
+ ) external returns (int64 responseCode);
+
+ /// Transfers `serialNumber` of `token` from `from` to `to` using the allowance mechanism.
+ /// Only applicable to NFT tokens
+ /// @param token The address of the non-fungible Hedera token to transfer
+ /// @param from The account address of the owner of `serialNumber` of `token`
+ /// @param to The account address of the receiver of `serialNumber`
+ /// @param serialNumber The NFT serial number to transfer
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function transferFromNFT(address token, address from, address to, uint256 serialNumber) external returns (int64 responseCode);
+
+ /// Get the approved address for a single NFT
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to check approval
+ /// @param serialNumber The NFT to find the approved address for
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return approved The approved address for this NFT, or the zero address if there is none
+ function getApproved(address token, uint256 serialNumber)
+ external
+ returns (int64 responseCode, address approved);
+
+ /// Enable or disable approval for a third party ("operator") to manage
+ /// all of `msg.sender`'s assets
+ /// @param token The Hedera NFT token address to approve
+ /// @param operator Address to add to the set of authorized operators
+ /// @param approved True if the operator is approved, false to revoke approval
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function setApprovalForAll(
+ address token,
+ address operator,
+ bool approved
+ ) external returns (int64 responseCode);
+
+ /// Query if an address is an authorized operator for another address
+ /// Only Applicable to NFT Tokens
+ /// @param token The Hedera NFT token address to approve
+ /// @param owner The address that owns the NFTs
+ /// @param operator The address that acts on behalf of the owner
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return approved True if `operator` is an approved operator for `owner`, false otherwise
+ function isApprovedForAll(
+ address token,
+ address owner,
+ address operator
+ ) external returns (int64 responseCode, bool approved);
+
+ /// Query if token account is frozen
+ /// @param token The token address to check
+ /// @param account The account address associated with the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return frozen True if `account` is frozen for `token`
+ function isFrozen(address token, address account)
+ external
+ returns (int64 responseCode, bool frozen);
+
+ /// Query if token account has kyc granted
+ /// @param token The token address to check
+ /// @param account The account address associated with the token
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return kycGranted True if `account` has kyc granted for `token`
+ function isKyc(address token, address account)
+ external
+ returns (int64 responseCode, bool kycGranted);
+
+ /// Operation to delete token
+ /// @param token The token address to be deleted
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function deleteToken(address token) external returns (int64 responseCode);
+
+ /// Query token custom fees
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return fixedFees Set of fixed fees for `token`
+ /// @return fractionalFees Set of fractional fees for `token`
+ /// @return royaltyFees Set of royalty fees for `token`
+ function getTokenCustomFees(address token)
+ external
+ returns (int64 responseCode, FixedFee[] memory fixedFees, FractionalFee[] memory fractionalFees, RoyaltyFee[] memory royaltyFees);
+
+ /// Query token default freeze status
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return defaultFreezeStatus True if `token` default freeze status is frozen.
+ function getTokenDefaultFreezeStatus(address token)
+ external
+ returns (int64 responseCode, bool defaultFreezeStatus);
+
+ /// Query token default kyc status
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return defaultKycStatus True if `token` default kyc status is KycNotApplicable and false if Revoked.
+ function getTokenDefaultKycStatus(address token)
+ external
+ returns (int64 responseCode, bool defaultKycStatus);
+
+ /// Query token expiry info
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return expiry Expiry info for `token`
+ function getTokenExpiryInfo(address token)
+ external
+ returns (int64 responseCode, Expiry memory expiry);
+
+ /// Query fungible token info
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return fungibleTokenInfo FungibleTokenInfo info for `token`
+ function getFungibleTokenInfo(address token)
+ external
+ returns (int64 responseCode, FungibleTokenInfo memory fungibleTokenInfo);
+
+ /// Query token info
+ /// @param token The token address to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenInfo TokenInfo info for `token`
+ function getTokenInfo(address token)
+ external
+ returns (int64 responseCode, TokenInfo memory tokenInfo);
+
+ /// Query token KeyValue
+ /// @param token The token address to check
+ /// @param keyType The keyType of the desired KeyValue
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return key KeyValue info for key of type `keyType`
+ function getTokenKey(address token, uint keyType)
+ external
+ returns (int64 responseCode, KeyValue memory key);
+
+ /// Query non fungible token info
+ /// @param token The token address to check
+ /// @param serialNumber The NFT serialNumber to check
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return nonFungibleTokenInfo NonFungibleTokenInfo info for `token` `serialNumber`
+ function getNonFungibleTokenInfo(address token, int64 serialNumber)
+ external
+ returns (int64 responseCode, NonFungibleTokenInfo memory nonFungibleTokenInfo);
+
+ /// Operation to freeze token account
+ /// @param token The token address
+ /// @param account The account address to be frozen
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function freezeToken(address token, address account)
+ external
+ returns (int64 responseCode);
+
+ /// Operation to unfreeze token account
+ /// @param token The token address
+ /// @param account The account address to be unfrozen
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function unfreezeToken(address token, address account)
+ external
+ returns (int64 responseCode);
+
+ /// Operation to grant kyc to token account
+ /// @param token The token address
+ /// @param account The account address to grant kyc
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function grantTokenKyc(address token, address account)
+ external
+ returns (int64 responseCode);
+
+ /// Operation to revoke kyc to token account
+ /// @param token The token address
+ /// @param account The account address to revoke kyc
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function revokeTokenKyc(address token, address account)
+ external
+ returns (int64 responseCode);
+
+ /// Operation to pause token
+ /// @param token The token address to be paused
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function pauseToken(address token) external returns (int64 responseCode);
+
+ /// Operation to unpause token
+ /// @param token The token address to be unpaused
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function unpauseToken(address token) external returns (int64 responseCode);
+
+ /// Operation to wipe fungible tokens from account
+ /// @param token The token address
+ /// @param account The account address to revoke kyc
+ /// @param amount The number of tokens to wipe
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function wipeTokenAccount(
+ address token,
+ address account,
+ int64 amount
+ ) external returns (int64 responseCode);
+
+ /// Operation to wipe non fungible tokens from account
+ /// @param token The token address
+ /// @param account The account address to revoke kyc
+ /// @param serialNumbers The serial numbers of token to wipe
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function wipeTokenAccountNFT(
+ address token,
+ address account,
+ int64[] memory serialNumbers
+ ) external returns (int64 responseCode);
+
+ /// Operation to update token info
+ /// @param token The token address
+ /// @param tokenInfo The hedera token info to update token with
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function updateTokenInfo(address token, HederaToken memory tokenInfo)
+ external
+ returns (int64 responseCode);
+
+ /// Operation to update token expiry info
+ /// @param token The token address
+ /// @param expiryInfo The hedera token expiry info
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function updateTokenExpiryInfo(address token, Expiry memory expiryInfo)
+ external
+ returns (int64 responseCode);
+
+ /// Operation to update token expiry info
+ /// @param token The token address
+ /// @param keys The token keys
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ function updateTokenKeys(address token, TokenKey[] memory keys)
+ external
+ returns (int64 responseCode);
+
+ /// Query if valid token found for the given address
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return isToken True if valid token found for the given address
+ function isToken(address token)
+ external returns
+ (int64 responseCode, bool isToken);
+
+ /// Query to return the token type for a given address
+ /// @param token The token address
+ /// @return responseCode The response code for the status of the request. SUCCESS is 22.
+ /// @return tokenType the token type. 0 is FUNGIBLE_COMMON, 1 is NON_FUNGIBLE_UNIQUE, -1 is UNRECOGNIZED
+ function getTokenType(address token)
+ external returns
+ (int64 responseCode, int32 tokenType);
+}
\ No newline at end of file
diff --git a/tests/unit/utils/solc/hts/Unused.sol b/tests/unit/utils/solc/hts/Unused.sol
new file mode 100644
index 000000000..8f27c8ef0
--- /dev/null
+++ b/tests/unit/utils/solc/hts/Unused.sol
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity ^0.8.17;
+
+contract HelloWorld {
+
+ string public message;
+
+ constructor(string memory initMessage) {
+
+ message = initMessage;
+ }
+
+ function update(string memory newMessage) public {
+ message = newMessage;
+ }
+}
+
diff --git a/vite.config.ts b/vite.config.ts
index 41b657309..fc9ef1a97 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -43,5 +43,8 @@ export default defineConfig({
'import.meta.env.VITE_BUILD_SHORTCOMMITHASH': JSON.stringify(commitHash),
'import.meta.env.VITE_BUILD_RELEASE': JSON.stringify(tagAndCommitHash),
'import.meta.env.VITE_BUILD_TIME_UTC': JSON.stringify(buildDate),
+ },
+ worker: {
+ format: "es",
}
})
diff --git a/vitest.config.ts b/vitest.config.ts
index f2fcd6d34..6b0876a1f 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -11,7 +11,7 @@ export default mergeConfig(
// cache: false, // If test fails in CI only, run locally with cache=false to be closer to CI environment
exclude: [...configDefaults.exclude, 'e2e/*'],
root: fileURLToPath(new URL('./', import.meta.url)),
- setupFiles: ['./tests/unit/globalSetup.js'],
+ setupFiles: ['./tests/unit/globalSetup.js', '@vitest/web-worker'],
coverage: {
reporter: ['text', 'json-summary', 'json'],
}