当前位置:优学网  >  在线题库

solc或py-solc-x存在以下问题

发表时间:2022-07-31 00:00:31 阅读:195

面对以下问题,python编程具有稳定性.solcjs——版本为0.8.15+commit.e14f2714.Emscripten.当py-solc-x==1.1.1和solc==0.0.0a0时发出叮当声

PS C:\Users\Hemali\Desktop\Smartmeter_codes> python3 SC_Submit_github.py
INFO: Could not find files for the given pattern(s).
True
7
Traceback (most recent call last):
  File "C:\Users\Hemali\Desktop\Smartmeter_codes\SC_Submit_github.py", line 67, in <module>
    compiled_sol = compile_source_file(contract_source_path)
  File "C:\Users\Hemali\Desktop\Smartmeter_codes\SC_Submit_github.py", line 37, in compile_source_file
    return compile_source(source)
  File "C:\Users\Hemali\Desktop\Smartmeter_codes\solcx\main.py", line 112, in compile_source
    return _compile_combined_json(
  File "C:\Users\Hemali\Desktop\Smartmeter_codes\solcx\main.py", line 277, in _compile_combined_json
    combined_json = _get_combined_json_outputs(solc_binary)
  File "C:\Users\Hemali\Desktop\Smartmeter_codes\solcx\main.py", line 242, in _get_combined_json_outputs
    help_str = wrapper.solc_wrapper(solc_binary=solc_binary, help=True)[0].split("\n")
  File "C:\Users\Hemali\Desktop\Smartmeter_codes\solcx\wrapper.py", line 158, in solc_wrapper
    raise SolcError(
solcx.exceptions.SolcError: An error occurred during execution
> command: `C:\Users\Hemali\.solcx\solc-v0.8.15\solc.exe --help -`
> return code: `0`
> stdout:
solc, the Solidity commandline compiler.

This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you
are welcome to redistribute it under certain conditions. See 'solc --license'
for details.

Usage: solc [options] [input_file...]
Compiles the given Solidity input files (or the standard input if none given or
"-" is used as a file name) and outputs the components specified in the options
at standard output or in files in the output directory, if specified.
Imports are automatically read from the filesystem, but it is also possible to
remap paths using the context:prefix=path syntax.
Example:
solc --bin -o /tmp/solcoutput dapp-bin=/usr/local/lib/dapp-bin contract.sol

General Information:
  --help               Show help message and exit.
  --version            Show version and exit.
  --license            Show licensing information and exit.
  --input-file arg     input file

Input Options:
  --base-path path     Use the given path as the root of the source tree
                       instead of the root of the filesystem.
  --include-path path  Make an additional source directory available to the
                       default import callback. Use this option if you want to
                       import contracts whose location is not fixed in relation
                       to your main source tree, e.g. third-party libraries
                       installed using a package manager. Can be used multiple
                       times. Can only be used if base path has a non-empty
                       value.
  --allow-paths path(s)
                       Allow a given path for imports. A list of paths can be
                       supplied by separating them with a comma.
  --ignore-missing     Ignore missing files.
  --error-recovery     Enables additional parser error recovery.

Output Options:
  -o [ --output-dir ] path
                       If given, creates one file per component and
                       contract/file at the specified directory.
  --overwrite          Overwrite existing files (used together with -o).
  --evm-version version (=london)
                       Select desired EVM version. Either homestead,
                       tangerineWhistle, spuriousDragon, byzantium,
                       constantinople, petersburg, istanbul, berlin or london.
  --experimental-via-ir
                       Deprecated synonym of --via-ir.
  --via-ir             Turn on compilation mode via the IR.
  --revert-strings debug,default,strip,verboseDebug
                       Strip revert (and require) reason strings or add
                       additional debugging information.
  --debug-info arg (=ast-id,location,snippet)
                       Debug info components to be included in the produced EVM
                       assembly and Yul code. Value can be all, none or a
                       comma-separated list containing one or more of the
                       following components: ast-id, location, snippet.
  --stop-after stage   Stop execution after the given compiler stage. Valid
                       options: "parsing".

Alternative Input Modes:
  --standard-json      Switch to Standard JSON input / output mode, ignoring
                       all options. It reads from standard input, if no input
                       file was given, otherwise it reads from the provided
                       input file. The result will be written to standard
                       output.
  --link               Switch to linker mode, ignoring all options apart from
                       --libraries and modify binaries in place.
  --assemble           Switch to assembly mode, ignoring all options except
                       --machine, --yul-dialect, --optimize and
                       --yul-optimizations and assumes input is assembly.
  --yul                Switch to Yul mode, ignoring all options except
                       --machine, --yul-dialect, --optimize and
                       --yul-optimizations and assumes input is Yul.
  --strict-assembly    Switch to strict assembly mode, ignoring all options
                       except --machine, --yul-dialect, --optimize and
                       --yul-optimizations and assumes input is strict
                       assembly.
  --import-ast         Import ASTs to be compiled, assumes input holds the AST
                       in compact JSON format. Supported Inputs is the output
                       of the --standard-json or the one produced by
                       --combined-json ast
  --lsp                Switch to language server mode ("LSP"). Allows the
                       compiler to be used as an analysis backend for your
                       favourite IDE.

Assembly Mode Options:
  --machine evm,ewasm  Target machine in assembly or Yul mode.
  --yul-dialect evm,ewasm
                       Input dialect to use in assembly or yul mode.

Linker Mode Options:
  --libraries libs     Direct string or file containing library addresses.
                       Syntax: <libraryName>=<address> [, or whitespace] ...
                       Address is interpreted as a hex string prefixed by 0x.

Output Formatting:
  --pretty-json        Output JSON in pretty format.
  --json-indent N (=2) Indent pretty-printed JSON with N spaces. Enables
                       '--pretty-json' automatically.
  --color              Force colored output.
  --no-color           Explicitly disable colored output, disabling terminal
                       auto-detection.
  --error-codes        Output error codes.

Output Components:
  --ast-compact-json   AST of all source files in a compact JSON format.
  --asm                EVM assembly of the contracts.
  --asm-json           EVM assembly of the contracts in JSON format.
  --opcodes            Opcodes of the contracts.
  --bin                Binary of the contracts in hex.
  --bin-runtime        Binary of the runtime part of the contracts in hex.
  --abi                ABI specification of the contracts.
  --ir                 Intermediate Representation (IR) of all contracts.
  --ir-optimized       Optimized intermediate Representation (IR) of all
                       contracts.
  --ewasm              Ewasm text representation of all contracts
                       (EXPERIMENTAL).
  --ewasm-ir           Intermediate representation (IR) converted to a form
                       that can be translated directly into Ewasm text
                       representation (EXPERIMENTAL).
  --hashes             Function signature hashes of the contracts.
  --userdoc            Natspec user documentation of all contracts.
  --devdoc             Natspec developer documentation of all contracts.
  --metadata           Combined Metadata JSON whose Swarm hash is stored
                       on-chain.
  --storage-layout     Slots, offsets and types of the contract's state
                       variables.

Extra Output:
  --gas                Print an estimate of the maximal gas usage for each
                       function.
  --combined-json abi,asm,ast,bin,bin-runtime,devdoc,function-debug,function-debug-runtime,generated-sources,generated-sources-runtime,hashes,metadata,opcodes,srcmap,srcmap-runtime,storage-layout,userdoc
                       Output a single json document containing the specified
                       information.

Metadata Options:
  --metadata-hash ipfs,none,swarm
                       Choose hash method for the bytecode metadata or disable
                       it.
  --metadata-literal   Store referenced sources as literal data in the metadata
                       output.

Optimizer Options:
  --optimize           Enable bytecode optimizer.
  --optimize-runs n (=200)
                       The number of runs specifies roughly how often each
                       opcode of the deployed code will be executed across the
                       lifetime of the contract. Lower values will optimize
                       more for initial deployment cost, higher values will
                       optimize more for high-frequency usage.
  --optimize-yul       Legacy option, ignored. Use the general --optimize to
                       enable Yul optimizer.
  --no-optimize-yul    Disable Yul optimizer in Solidity.
  --yul-optimizations steps
                       Forces yul optimizer to use the specified sequence of
                       optimization steps instead of the built-in one.

Model Checker Options:
  --model-checker-contracts default,<source>:<contract> (=default)
                       Select which contracts should be analyzed using the form
                       <source>:<contract>.Multiple pairs <source>:<contract>
                       can be selected at the same time, separated by a comma
                       and no spaces.
  --model-checker-div-mod-no-slacks
                       Encode division and modulo operations with their precise
                       operators instead of multiplication with slack
                       variables.
  --model-checker-engine all,bmc,chc,none (=none)
                       Select model checker engine.
  --model-checker-invariants default,all,contract,reentrancy (=default)
                       Select whether to report inferred contract inductive
                       invariants. Multiple types of invariants can be selected
                       at the same time, separated by a comma and no spaces. By
                       default no invariants are reported.
  --model-checker-show-unproved
                       Show all unproved targets separately.
  --model-checker-solvers all,cvc4,z3,smtlib2 (=all)
                       Select model checker solvers.
  --model-checker-targets default,all,constantCondition,underflow,overflow,divByZero,balance,assert,popEmptyArray,outOfBounds (=default)
                       Select model checker verification targets. Multiple
                       targets can be selected at the same time, separated by a
                       comma and no spaces. By default all targets except
                       underflow and overflow are selected.
  --model-checker-timeout ms
                       Set model checker timeout per query in milliseconds. The
                       default is a deterministic resource limit. A timeout of
                       0 means no resource/time restrictions for any query.

> stderr:
PS C:\Users\Hemali\Desktop\Smartmeter_codes

上述错误代码的代码为

# """ Before running this, you need to install Ganache to run a local Blockchain. Otherwise, use infura to access a node. """
# Here, addresses match the local Ganache Blockchain.
# Then, You should (maybe) install solc (open a powershell terminal or a cmd, and run "pip install solc")
# Then, You should (definitely) install solcx (open a powershell terminal or a cmd, and run "pip install py-solc-x")  https://pypi.org/project/py-solc-x/
# Finally, you should change the paths that are listed below to locate the solidity SC (here, Greeting.sol).
import json
import time
import pprint
from web3 import Web3
from solcx import compile_source, compile_files
from solcx import install_solc
install_solc("0.8.14")

#########################  To Run the interaction with Matlab ############################
# First, follow the instructions below: https://uk.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html 
# 1. Make sure you have Python in your PATH.
# 2. Find the Matlab root folder. You can use the matlabroot command within Matlab to find it.
# 3. In the windows Command line ("cmd" opened with admin rights) Go to the Matlab root folder in the command line by typing cd "matlabroot\extern\engines\python" (In Windows)
# 4. Type in python setup.py install 
# 6. In matlab (opened with admin rights ) type in :cd (fullfile(matlabroot,'extern','engines','python'))
#                                                      system('python setup.py install')
# Then, uncomment the 2 following lines:
""" import matlab.engine
matlab_eng = matlab.engine.start_matlab() """

# This Smart Contract aims to:
# 1. Open a Market Place as defined in SC_1_Bid_and_Payment.sol
# 2. Submit bids from 2 agents (1 seller 1 buyer)
# 3. retrieve the bids (by the DSO/operator) 

def compile_source_file(file_path):
   with open(file_path, 'r') as f:
      source = f.read()

   return compile_source(source)

def deploy_contract(w3, contract_interface):
    tx_hash = w3.eth.contract(
        abi=contract_interface['abi'],
        bytecode=contract_interface['bin']).constructor().transact()
#functions.transact() executes the specified function by sending a new public transaction.
    address = w3.eth.getTransactionReceipt(tx_hash)['contractAddress']
    return address

# Connection to he Local Ganache Blockchain
ganache_url = "HTTP://127.0.0.1:7545"
w3 = Web3(Web3.HTTPProvider(ganache_url))
print(w3.isConnected())
print(w3.eth.blockNumber)

# We define the agent's accounts
# The operator/DSO:
w3.eth.defaultAccount = w3.eth.accounts[0]
# The Seller:
SellerAgentAccount = w3.eth.accounts[1]
# The Buyer:
BuyerAgentAccount = w3.eth.accounts[2]

# Compile the contract
contract_source_path = r'C:\Users\Hemali\Desktop\Smartmeter_codes\NegotiationMarketPlace.sol'
compiled_sol = compile_source_file(contract_source_path)
contract_id, contract_interface = compiled_sol.popitem()

# retrieve the compilation results (abi and bytecode)
abi = contract_interface['abi']
bytecode = contract_interface['bin']
# print(abi)
# Deployment of the contract
address = deploy_contract(w3, contract_interface)
contract = w3.eth.contract(
    address = address,
    abi = abi
)

print("Deployed {0} to: {1}\n".format(contract_id, address))
gas_estimate = contract.functions.submitBid(10, 10, 1, 0).estimateGas() #submitbid the function defined in the SC_1_Bid_and_Payment.sol smart contract - 
# arg(1) =10 is the bid price
# arg(2) =10 is the bidQuantity
# arg(3) =1 is the bidWeight
# arg(4) =0 is the agent type (0 for seller, 1 for buyer)
print("Gas estimate to transact with submitBid: {0}\n".format(gas_estimate))

if gas_estimate < 200000:
    # The seller submits his offer:
  print("Submitting Offer from Seller\n")
  tx_hash = contract.functions.submitBid(10, 10, 1, 0).transact({'from': SellerAgentAccount}) # the 
  #functions.transact() executes the specified function by sending a new public transaction.
  receipt = w3.eth.waitForTransactionReceipt(tx_hash)
# arg(1) =10 is the bid price
# arg(2) =10 is the bidQuantity
# arg(3) =1 is the bidWeight
# arg(4) =0 is the agent type  (0 for seller, 1 for buyer)
  # The buyer submits his bid
  tx_hash = contract.functions.submitBid(1, 5, 1, 1).transact({'from': BuyerAgentAccount})
  receipt = w3.eth.waitForTransactionReceipt(tx_hash)
  """   print("Transaction receipt mined: \n")
  pprint.pprint(dict(receipt))
  print("Was transaction successful? \n")
  pprint.pprint(receipt['status']) """
else:
  print("Gas cost exceeds 200000")

# Now the Operator/DSO retrieves the bids
# First retrieves the seller's bid
tx_hash = contract.functions.retrievebid(SellerAgentAccount).transact()
receipt = w3.eth.waitForTransactionReceipt(tx_hash)
sellerData = contract.functions.retrievebid(SellerAgentAccount).call()
# Then retrieves the Buyer's bid
tx_hash = contract.functions.retrievebid(BuyerAgentAccount).transact()
receipt = w3.eth.waitForTransactionReceipt(tx_hash)
buyerData = contract.functions.retrievebid(BuyerAgentAccount).call()

# we check that the DSO retrieve the buyer's
print(contract.functions.retrievebid(BuyerAgentAccount).call())

# Then, the DSO/Operator realizes the negotiations and validation of the grid offline (Matlab code)
# We send the values to Matlab, and retrieve the price to pay. 
Price_to_pay = 19
# #If using Matlab, please uncomment the following line
""" Price_to_pay = matlab_eng.Compute_Price_to_Pay(buyerData,sellerData)"""
print(Price_to_pay)

# Then, we will proceed to the payment using the Smart Contract

solidity文件在Ganache中编译和部署.对于该项目,我正在使用Visual Studio代码和Windows 10 Pro中的Ganache provider.

实体文件如下所示:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract NegotiationMarketPlace {
    // The Market place stores the count of all the buyers, sellers who sent bids
    uint8 private buyerCount;
    uint8 private sellerCount;
    // The market place stores (with a hash) the bid (price and quantity, we also need the weights (or Beta) and other informations to be added), and the type of the agent (Buyer (1) or Seller (0))
    mapping (address => uint) private bidPrice;
    mapping (address => uint) private bidQuantity;
    mapping (address => uint) private bidWeight;
    mapping (address => uint) public agentType;
    // The market place is owned by the DSO Agent:
    address payable public dsoAgent;
    // We store all agent's addresses in a list
    address[] public agentsList;
    // We also need to add a time: Times are either absolute unix timestamps (seconds since 1970-01-01) or time periods in seconds.
    uint public marketEndTime; // not used yet

    // Log the event about a bid being made by an address (Agent) and its amount
    event LogBidMade(address indexed accountAddress, uint price, uint quantity, uint Weight); // Notice that weights are uint for now, as fixed point are not yet fully implemented (=> the DSO will divide by 10)

    // We need  a boolean to state the stage of the market place (open or not for receiving new offers/bids) Set to true at the end, disallows any change. By default initialized to `false`.
    bool ended;

    //  We create a modifier that could be used later to restrict some functions to only the operator. not needed for simple use
    modifier onlyOperator() {
        require(
            msg.sender == dsoAgent,
            "Only DSO/Operator can call this."
        );
        _;
    }

    // Constructor function to initialize the MarketPlace. It is "payable" so it can receive initial funding to cover up some mispayment
    constructor() payable {
       // require(msg.value == 10 ether, "10 ether initial funding required");
        /* Set the owner to the creator of this contract */
        dsoAgent = payable(msg.sender);
        // initialization of variables
        buyerCount = 0;
        sellerCount = 0;
    }

    ///  Creation of a bid from an agent return The type of the agent (1 or 0)
    function submitBid(uint _bidprice, uint _bidquantity, uint _bidweight, uint _agenttype) public returns (uint) {
        if (_agenttype == 1) {
            buyerCount++;}
        else  {
            sellerCount++;
        }
        // We update all values of this agent
        bidPrice[msg.sender] = _bidprice;
        bidQuantity[msg.sender] = _bidquantity;
        bidWeight[msg.sender] = _bidweight;
        agentType[msg.sender] = _agenttype;

        return agentType[msg.sender];
    }

// The operator or DSO wants to retrieve all the bids. However, mapping does not allow to do that. Hence, we can either store each bid/agent into an iterable mapping
// as shown here https://medium.com/rayonprotocol/creating-a-smart-contract-having-iterable-mapping-9b117a461115 or also the github (https://github.com/ethereum/dapp-bin/blob/master/library/iterable_mapping.sol)
// or the operator/DSO makes as many requests to this Smart Contract to retrieve all the bids from all the registered agents. And if an agent has not placed a bid, it returns 0
    function retrievebid(address agentaddress) onlyOperator public view returns(uint[4] memory) {
        uint[4] memory array;
        if (bidPrice[agentaddress] != 0){
            array = [bidPrice[agentaddress], bidQuantity[agentaddress],bidWeight[agentaddress],agentType[agentaddress]];
        }
            return array;
    }

// After negotiations, the DSO/operator wants to activate payment between agents, while specifying the amount
}

/*     // The following comment is a so-called natspec comment, recognizable by the three slashes. It will be shown when the user is asked to confirm a transaction.
    /// Create a simple MarketPlace with `_marketEndTime` seconds bidding time 
    constructor(
        uint _marketEndTime,
   //     address payable _beneficiary
    ) public {
     //   beneficiary = _beneficiary;
        marketEndTime = now + _marketEndTime;
    } */
🎖️ 优质答案
相关问题