Example #1
0
def TestBuild(script,
              invoke_args,
              wallet,
              plist='05',
              ret='05',
              dynamic=False,
              invoke_attrs=None,
              owners=None):

    properties = ContractPropertyState.HasStorage

    if dynamic:
        properties += ContractPropertyState.HasDynamicInvoke

    if not isinstance(ret, bytearray):
        ret = bytearray(binascii.unhexlify(str(ret).encode('utf-8')))

    script = generate_deploy_script(script,
                                    contract_properties=int(properties),
                                    parameter_list=plist,
                                    return_type=BigInteger.FromBytes(ret))

    return test_deploy_and_invoke(script,
                                  invoke_args,
                                  wallet,
                                  invoke_attrs=invoke_attrs,
                                  owners=owners)
Example #2
0
def TestBuild(script, invoke_args, wallet, plist='05', ret='05', dynamic=False):

    properties = ContractPropertyState.HasStorage

    if dynamic:
        properties += ContractPropertyState.HasDynamicInvoke

    script = generate_deploy_script(script, contract_properties=int(properties), parameter_list=plist, return_type=ret)

    return test_deploy_and_invoke(script, invoke_args, wallet)
Example #3
0
def TestBuild(script, invoke_args, wallet, plist='05', ret='05', dynamic=False):

    properties = ContractPropertyState.HasStorage

    if dynamic:
        properties += ContractPropertyState.HasDynamicInvoke

    if not isinstance(ret, bytearray):
        ret = bytearray(binascii.unhexlify(str(ret).encode('utf-8')))

    script = generate_deploy_script(script, contract_properties=int(properties), parameter_list=plist, return_type=ret)

    return test_deploy_and_invoke(script, invoke_args, wallet)
Example #4
0
    def worker(self):
        self.chain.Pause()
        BuildAndRun(self.args, wallet=self.wallet, verbose=True)
        self.chain.Resume()

        avm_path = self.scPath.replace('.py', '.avm')
        self.args[0] = avm_path

        from_addr = None

        current_height = 0
        code = LoadContract(args=self.args)
        # /scripts/sc.avm 0710 02 True False False
        if code:
            script = generate_deploy_script(
                code.Script,
                "myTestSmartContract",  # name
                "test",  # version
                "",  # author
                "",  # email
                "",  # description
                code.ContractProperties,
                code.ReturnTypeBigInteger,
                code.ParameterList)
            if script is not None:
                tx, fee, results, num_ops = test_invoke(script,
                                                        self.wallet, [],
                                                        from_addr=from_addr)
                if tx is not None and results is not None:
                    print("Test deploy invoke successful")
                    print("Deploy Invoke TX GAS cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print("-------------------------")
                    while not self.isSynced:
                        self.show_state()
                        time.sleep(1)
                    result = InvokeContract(self.wallet,
                                            tx,
                                            Fixed8.Zero(),
                                            from_addr=from_addr)
                    print("Result: ", result.ToJson(), self.isSynced)
                    print("Result: ", tx.ToJson())
                    current_height = self.chain.Height + 1

            print("Script:", script)
        # we expect the transaction to be included in the next block:
        while current_height > self.chain.Height:
            self.show_state()
            time.sleep(5)
        self.twist.stop()
Example #5
0
    def autoDeploy(self):
        self.Wallet.Rebuild()
        function_code = LoadContract([neo_fund_avm, '0710', '05', 'True'])
        self.contract_script = generate_deploy_script(
            function_code.Script, 'NeoFund', str(int(time.time())), 'Nick',
            '*****@*****.**', 'auto deploy', True,
            ord(function_code.ReturnType), function_code.ParameterList)

        if self.contract_script is not None:
            self.neo_fund_sc = function_code.ToJson()['hash']
            # self.neo_fund_sc_addr = ImportContractAddr(self.Wallet, [self.neo_fund_sc, test_pub_addr]).Address

            print('SC Hash: ', self.neo_fund_sc)
            # print('SC Addr: ',  self.neo_fund_sc_addr)

        return self.contract_script
def construct_deploy_tx(wallet, params):
    params = params[0]
    from_addr = params['from_addr']
    # load_smart_contract
    contract_params = bytearray(binascii.unhexlify(params['contract_params']))
    return_type = bytearray(binascii.unhexlify(params['return_type']))
    
    contract_properties = 0
    if params.get('needs_storage', True):
        contract_properties += ContractPropertyState.HasStorage
    if params.get('needs_dynamic_invoke', False):
        contract_properties += ContractPropertyState.HasDynamicInvoke

    script = binascii.unhexlify(params['bin'])

    function_code = FunctionCode(
            script = script,
            param_list = contract_params,
            return_type = return_type,
            contract_properties = contract_properties,
    )

    if Blockchain.Default().GetContract(function_code.ScriptHash().To0xString()):
        raise Exception('contract already exists')

    # GatherContractDetails
    details = params['details']
    name = details['name']
    version = details['version']
    author = details['author']
    email = details['email']
    description = details['description']

    contract_script = generate_deploy_script(
            function_code.Script,
            name,
            version,
            author,
            email,
            description,
            function_code.ContractProperties,
            function_code.ReturnType,
            function_code.ParameterList,
    )

    # test_invoke    
    bc = GetBlockchain()
    sn = bc._db.snapshot()
    accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState)
    assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState)
    validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState)
    contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState)
    storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem)


    tx = InvocationTransaction()
    tx.outputs = []
    tx.inputs = []
    tx.Version = 1
    tx.scripts = []
    tx.Script = binascii.unhexlify(contract_script)

    script_table = CachedScriptTable(contracts)
    service = StateMachine(accounts, validators, assets, contracts, storages, None)
    contract = wallet.GetDefaultContract()
    tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script, unhex=False).Data)]
    tx = wallet.MakeTransaction(tx=tx)

    engine = ApplicationEngine(
            trigger_type=TriggerType.Application,
            container=tx,
            table=script_table,
            service=service,
            gas=tx.Gas,
            testMode=True
    )   
    engine.LoadScript(tx.Script, False)
    success = engine.Execute()
    if not success:
        raise Exception('exec failed')
    
    service.ExecutionCompleted(engine, success)

    consumed = engine.GasConsumed() - Fixed8.FromDecimal(10)
    consumed = consumed.Ceil()

    net_fee = None
    tx_gas = None

    if consumed <= Fixed8.Zero():
        net_fee = Fixed8.FromDecimal(.0001)
        tx_gas = Fixed8.Zero()
    else:
        tx_gas = consumed
        net_fee = Fixed8.Zero()
    tx.Gas = tx_gas
    tx.outputs = []
    tx.Attributes = []

    # InvokeContract
    from_addr = lookup_addr_str(wallet, from_addr)
    tx = wallet.MakeTransaction(tx=tx, fee=net_fee, use_standard=True, from_addr=from_addr)
    if tx is None:
        raise Exception("no gas")


    context = ContractParametersContext(tx)
    ms = StreamManager.GetStream()
    writer = BinaryWriter(ms)
    tx.Serialize(writer)
    ms.flush()
    binary_tx = ms.ToArray()
    return {'context': context.ToJson(), 'tx': binary_tx.decode(), 'hash': function_code.ScriptHash().To0xString()}