def test_close(self): from contract import Contract contract = Contract(stubs.SENDER, "", "", "", "", "", "") contract.close("foo") assert contract._close == "foo" contract = Contract("yolo", "", "", "", "", "", "") try: contract.close("foo") assert 0 except Exception as e: assert e.args[0] == 'Only admin can call this entrypoint'
def main(): contract = Contract(ProviderOne()) cost_providerone = Contract(ProviderOne()).provider cost_providertwo = Contract(ProviderTwo()).provider cost_providerthree = Contract(ProviderThree()).provider contract.number = 13456 assert cost_providerone == 10.00 assert cost_providertwo == 5.00 assert cost_providerthree == 7.0 bench1 = BenchMark('bench1') bench2 = BenchMark('bench2') print(bench1) print(bench2)
def test_artifacts(self): from contract import Contract contract = Contract(stubs.SENDER, "", "", "", "", "", "") contract.artifacts("url", "hash") assert contract.artifacts_url == "url" assert contract.artifacts_hash == "hash" contract = Contract("yolo", "", "", "", "", "", "") try: contract.artifacts("url", "hash") assert 0 except Exception as e: assert e.args[0] == 'Only admin can call this entrypoint'
def __init__(self, num, players, pins, game_header): self.num = num self.players = players self.pins = pins self.game_state = game_header # Useful string to have on hand self.scores = [0, 0] self.bags = [0, 0] self.winnings = {'A1': 0, 'B1': 0, 'A2': 0, 'B2': 0} self.contracts = [Contract(), Contract()] self.hands = {} self.spade_in_play = False # Answers: Has a spade been played yet this round? # Run the round self.run()
def test_open(self): from contract import Contract contract = Contract(stubs.SENDER, "", "", "", "", "", "") contract.open("foo", "bar", "baz") assert contract._open == "foo" assert contract.manifest_url == "bar" assert contract.manifest_hash == "baz" contract = Contract("yolo", "", "", "", "", "", "") try: contract.open("foo", "bar", "baz") assert 0 except Exception as e: assert e.args[0] == 'Only admin can call this entrypoint'
def __init__(self, filename, **kwargs): self.filename = filename self.wb = load_workbook(filename) self.contract = Contract(self.wb.get_sheet_by_name(self.CONTRACT)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS))
def process(self, input_paths, output_paths): # Init steps hs = HashtagSplit() nr = Normalize() ct = Contract() # execute pipeline for input_path, output_path in zip(input_paths, output_paths): # data paths path_0 = input_path path_1 = output_path[:-4] + '_1' + output_path[-4:] path_2 = output_path[:-4] + '_2' + output_path[-4:] path_3 = output_path # set paths hs.set_paths(path_0, path_1) nr.set_paths(path_1, path_2) ct.set_paths(path_2, path_3) # run print("starting with " + os.path.basename(input_path)) hs.run() print(os.path.basename(input_path) + ": hashtag done.") nr.run() print(os.path.basename(input_path) + ": normalize done.") ct.run() print(os.path.basename(input_path) + ": contract done.")
def generate_player(): r = random(); name = '' if r < 0.5: name = rand_male_name() + ' ' + rand_surname() else: name = rand_female_name() + ' ' + rand_surname() pos = Pos.rand_position() weight, height = 0, 0 if pos == Pos.CATCHER: weight, height = catcher_height_weight() elif Pos.is_infield(pos): weight, height = infield_height_weight() elif Pos.is_outfield(pos): weight, height = outfield_height_weight() else: weight, height = pitcher_height_weight() birthdate = generate_birthdate(start_date.year) bats, throws = generate_bats_throws() years_in_majors = int( gauss(years_old(birthdate, start_date) - 23, 2) ) if years_in_majors < 0: years_in_majors = 0 caps = Capabilities.generate_all_caps(height, weight, birthdate, start_date, years_in_majors, pos) pos_caps = PositionCapabilities.generate_pos_caps(pos) contract = Contract(get_FA(), 0, 0) personality = Personality.rand_personality() return Player(name, pos, height, weight, birthdate, bats, throws, caps, pos_caps, contract, personality)
def add_contract(source, destination, provider, payload, amount, signedContract): encode_data = ( source.encode() + destination.encode() + provider.encode() + payload.encode() + amount.encode() ) # TEST # if not verify_sign(provider, encode_data, signedContract): # return None # else: ######new_contract = Contract(str(time.time()), source, destination, provider, payload, amount) new_contract = Contract(str(123), source, destination, provider, payload, amount) token_ledger[source] = str(int(token_ledger[source]) - int(new_contract.stake)) token_ledger[destination] = str( int(token_ledger[destination]) - int(new_contract.stake) ) active_contract_list.append(new_contract.serialize()) block_data = generate_data( new_contract.serialize(), None, token_ledger, active_contract_list ) node_chain_instance.add_block(block_data) """ for i in range(len(node_chain_instance.block_data)): print(str(node_chain_instance.block_data[i])) #print((json.loads(node_chain_instance.block_data[-1].data)).get('ledger')) print((json.loads(node_chain_instance.block_data[-1].data))) """ return block_data
def upload(self, relativeFilePath, lookupKey = None, signatureKey = None, constructorArgs=[]): resolvedPath = resolveRelativePath(relativeFilePath) if self.coverageMode: resolvedPath = resolvedPath.replace("tests", "coverageEnv").replace("source/", "coverageEnv/") lookupKey = lookupKey if lookupKey else path.splitext(path.basename(resolvedPath))[0] signatureKey = signatureKey if signatureKey else lookupKey if lookupKey in self.contracts: return(self.contracts[lookupKey]) compiledCode = self.getCompiledCode(resolvedPath) # abstract contracts have a 0-length array for bytecode if len(compiledCode) == 0: if ("libraries" in relativeFilePath or lookupKey.startswith("I") or lookupKey.startswith("Base") or lookupKey.startswith("DS")): pass#print "Skipping upload of " + lookupKey + " because it had no bytecode (likely a abstract class/interface)." else: raise Exception("Contract: " + lookupKey + " has no bytecode, but this is not expected. It probably doesn't implement all its abstract methods") return None if signatureKey not in ContractsFixture.signatures: ContractsFixture.signatures[signatureKey] = self.generateSignature(resolvedPath) signature = ContractsFixture.signatures[signatureKey] W3Contract = self.w3.eth.contract(abi=signature, bytecode=compiledCode) deploy_address = self.accounts[0] tx_hash = W3Contract.constructor(*constructorArgs).transact({'from': deploy_address, 'gasPrice': 1, 'gas': 750000000}) tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash, 180) if tx_receipt.status == 0: raise Exception("Contract upload %s failed" % lookupKey) w3Contract = W3Contract(tx_receipt.contractAddress) contract = Contract(self.w3, w3Contract, self.logListener, self.coverageMode) self.contracts[lookupKey] = contract return contract
def checkScript(): script = request.form.get('script',default="") contract = Contract(script) result = contract.check() if result["errCode"]==0: return result["result"] else: return result["errText"]
def get_contract(contract_name: str) -> Contract: return Contract(account=ACCOUNT, private_key=ACCOUNT_PRIVATE_KEY, contract_name=contract_name, abi_file=os.path.join(ABI_DIR, f"{contract_name}.json"), bytecode_file=os.path.join(BIN_DIR, f"{contract_name}.bin"), rpc_url=RPC_URL)
def applySignature(self, signatureName, address, signature=None): assert address if signature is None: signature = ContractsFixture.signatures[signatureName] W3Contract = self.w3.eth.contract(abi=signature) w3Contract = W3Contract(address) contract = Contract(self.w3, w3Contract, self.logListener, self.coverageMode) return contract
def todo_test_approve(self): # make dataclasses hashable by default by ignoring `unsafe_hash` in dataclass param in compiler) amount = 10 contract = Contract(owner=admin, tokens={}, allowances={}, total_supply=0) contract.approve(investor, amount) assert contract.allowances[AllowanceKey(admin, investor)] == amount
def newTransaction(inPrvkey, inPubkey, outPubkey, amount, utxo, script=""): if script: contract = Contract(script) result = contract.check() if result["errCode"] != 0: return result ins = [] outs = [] inAddr = Wallet.address(inPubkey) outAddr = Wallet.address(outPubkey) todo = utxo.findSpendableOutputs(inAddr, amount) #todo={"acc":3,"unspend":{"3453425125":{"index":0,"amount":"3"}, # "2543543543":{"index":0,"amount":"2"} # } # } #print("newTransaction.todo","\n",todo) amount = round(amount, 4) if todo["acc"] < amount: Transaction.logger.warning("%s not have enough money." % inAddr) return {"errCode": 1, "errText": "not enough money."} for hash in todo["unspend"]: output = todo["unspend"][hash] prevHash = hash index = output["index"] toSign = prevHash + str(index) + inAddr sign = utils.sign(message=toSign, prvkey=inPrvkey) ins.append( TXin({ "prevHash": prevHash, "index": index, "inAddr": inAddr, "pubkey": inPubkey, "sign": sign })) outs.append( TXout({ "amount": round(amount, 4), "outAddr": outAddr, "script": script })) if todo["acc"] > amount: outs.append( TXout({ "amount": round(todo["acc"] - amount, 4), "outAddr": inAddr, "script": "" })) TX = Transaction(ins=ins, outs=outs) utxoSet = copy.deepcopy(utxo.utxoSet) if not utxo.updateWithTX(TX, utxoSet): return { "errCode": 1, "errText": "double spend!!,Maybe not enough money." } utxo.utxoSet = utxoSet return TX
def read_contracts(): contracts = pd.read_excel('contracts.xlsx') companies = contracts['Company Name'] start_dates = contracts['Start Date'] end_dates = contracts['End Date'] for i in range(len(companies)): contract = Contract(companies[i], start_dates[i], end_dates[i]) database.add_contract(contract)
def __init__(self, template, **kwargs): self.template = template #self.dest = dest self.wb = load_workbook(template) self.contract = Contract(self.wb.get_sheet_by_name( self.CONTRACT_SHEET)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE_SHEET)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS_SHEET))
def test_mint(self): from contract import Contract contract = Contract(owner=admin, tokens={}, allowances={}, total_supply=0) amount = 10 contract.mint(admin, amount) assert contract.tokens[admin] == amount contract = Contract(owner=investor, tokens={}, allowances={}, total_supply=0) try: contract.mint(admin, amount) assert 0 except Exception as e: assert e.args[0] == 'Only owner can mint'
def placeOneOrder(self): con = Contract() con.symbol = "AMD" con.secType = "STK" con.currency = "USD" con.exchange = "SMART" order = Order() order.action = "BUY" order.orderType = "LMT" order.tif = "GTC" order.totalQuantity = 3 order.lmtPrice = 1.23 self.placeOrder(self.nextOrderId(), con, order)
def wrapper(f): @warps(f) def _function(self, *args, **kwargs): return f(self, *args, **kwargs) if hasattr(f, 'contract'): contract = f.contract contract.setName(name) else: contract = Contract(name) _function.__dict__["contract"] = contract _function.func_name = f.func_name return _function
def wrapper(f): @wraps(f) def _function(self, *args, **kwargs): return f(self, *args, **kwargs) o = Output(name, type) if hasattr(f, 'contract'): contract = f.contract contract.addOutput(o) else: contract = Contract(f.__name__) _function.__dict__["contract"] = contract _function.func_name = f.func_name return _function
def canbeUnlockWith(self, address): if self.outAddr == address: if self.script == "": return True else: contract = Contract(self.script) result = contract.check() if result["errCode"] == 0: if result["result"] == "True": return True else: return False else: return False else: return False
def make_contract(self, curs, contract_type, fixed_holder, unfixed_holder, price, quantity): con = Contract(contract_type, fixed_holder, unfixed_holder, price, quantity).persist(curs) curs.execute( "UPDATE account SET balance = balance - %s WHERE id = %s", (price * quantity - con.fixed_refund * 1000, fixed_holder), ) curs.execute( "UPDATE account SET balance = balance - %s WHERE id = %s", ((1000 - price) * quantity - con.unfixed_refund * 1000, unfixed_holder), ) self.db.messages.add( "contract_created", fixed_holder, contract_type, self.db.FIXED, price, quantity, contract=con, ) self.db.messages.add( "contract_created", unfixed_holder, contract_type, self.db.UNFIXED, price, quantity, contract=con, ) if con.fixed_refund: self.db.messages.add( "position_covered", fixed_holder, contract_type, quantity=con.fixed_refund, contract=con, ) if con.unfixed_refund: self.db.messages.add( "position_covered", unfixed_holder, contract_type, quantity=con.unfixed_refund, contract=con, )
def generate_manager(): r = random() name = '' if r < 0.5: name = rand_male_name() + ' ' + rand_surname() else: name = rand_female_name() + ' ' + rand_surname() birthdate = generate_birthdate(start_date.year) qualities = [] for param in params(): qualities.append(redistribute(int(gauss(param[0], param[1])))) contract = Contract(get_FA(), 0, 0) return Manager(name, birthdate, qualities[0], qualities[1], qualities[2], qualities[3], qualities[4], qualities[5], qualities[6], contract)
def test_transfer(self): amount_1 = 10 contract = Contract(owner=admin, tokens={admin: amount_1}, allowances={}, total_supply=amount_1) investor = "Mr. Bar" amount_2 = 4 contract.transfer(admin, investor, amount_2) assert contract.tokens[admin] == amount_1 - amount_2 assert contract.tokens[investor] == amount_2 try: contract.transfer(admin, investor, 100) assert 0 except Exception as e: assert e.args[0] == 'NotEnoughBalance'
def create_transition_controller(self, start: Types, finish: Types, t_trans: int) -> Controller: t_controller_name = f"TRANS_{start.name}->{finish.name}" if self.session_name is None: folder_name = f"{self.t_controllers_folder_name}/{t_controller_name}" else: folder_name = f"{self.session_name}/{self.t_controllers_folder_name}/{t_controller_name}" typeset = Typeset({start, finish}) realizable = False for n_steps in range(1, t_trans): trans_spec_str = Logic.and_([start.name, Logic.xn_(finish.name, n_steps)]) trans_spec = Atom(formula=(trans_spec_str, typeset)) trans_contract = Contract(guarantees=trans_spec) try: controller_info = trans_contract.get_controller_info(world_ts=self.world.typeset) a, g, i, o = controller_info.get_strix_inputs() controller_synthesis_input = StringMng.get_controller_synthesis_str(controller_info) Store.save_to_file(controller_synthesis_input, f"t_controller_{start.name}_{finish.name}_specs.txt", folder_name) realized, kiss_mealy, time = Strix.generate_controller(a, g, i, o) if realized: realizable = True break except ControllerException as e: raise TransSynthesisFail(self, e) if not realizable: raise Exception( f"Controller [{start.name}, {finish.name}] cannot be synthetized in {t_trans} steps") else: Store.save_to_file(kiss_mealy, f"{start.name}_{finish.name}_mealy", folder_name) # Store.generate_eps_from_dot(dot_mealy, f"{start.name}_{finish.name}_dot", # folder_name) t_controller = Controller(mealy_machine=kiss_mealy, world=self.world, name=t_controller_name, synth_time=time) Store.save_to_file(str(t_controller), f"{start.name}_{finish.name}_table", folder_name) return t_controller
] schedule_processors = [] event_handlers = [ Approved, ApprovedError, ApprovedRejected, Canceled, Cosigned, Lent, ReadedOracle, Requested, SettledCancel, SettledLend, ApprovedByCallback, ApprovedBySignature, BorrowerByCallback, BorrowerBySignature, CreatorByCallback, CreatorBySignature ] loan_manager = Contract( "LoanManager", event_handlers, commit_processors, schedule_processors, contract_connection )
def test_timed(self): price_per_token = 1000 token_value = 2 #Tokens base_token = Contract("ERC20Mintable", w3, { "owner": w3.eth.accounts[0], "args": [] }) tether = Contract("ERC20Mintable", w3, { "owner": w3.eth.accounts[0], "args": [] }) base_token.instance.mint(w3.eth.accounts[0], 100, transact={'from': w3.eth.accounts[0]}) tether.instance.mint(w3.eth.accounts[1], 100000, transact={'from': w3.eth.accounts[0]}) #Crowdsale block = w3.eth.getBlock("latest")["timestamp"] timed_crowdsale = Contract( "TimedCrowdsale", w3, { "owner": w3.eth.accounts[0], "args": [ block + 5, block + 10, base_token.address, w3.eth.accounts[0], [tether.address], [price_per_token] ] }) base_token.instance.transfer(timed_crowdsale.address, 100, transact={'from': w3.eth.accounts[0]}) #before with self.assertRaises(ValueError): tether.instance.approve(timed_crowdsale.address, token_value * price_per_token, transact={'from': w3.eth.accounts[1]}) timed_crowdsale.instance.invest( token_value * price_per_token, tether.address, transact={'from': w3.eth.accounts[1]}) time.sleep(6) #opened tether.instance.approve(timed_crowdsale.address, token_value * price_per_token, transact={'from': w3.eth.accounts[1]}) timed_crowdsale.instance.invest(token_value * price_per_token, tether.address, transact={'from': w3.eth.accounts[1]}) time.sleep(6) #closed with self.assertRaises(ValueError): tether.instance.approve(timed_crowdsale.address, token_value * price_per_token, transact={'from': w3.eth.accounts[1]}) timed_crowdsale.instance.invest( token_value * price_per_token, tether.address, transact={'from': w3.eth.accounts[1]})
def main(): cmdLineParser = argparse.ArgumentParser("api tests") #cmdLineParser.add_option("-c", action="store_true", dest="use_cache", default = False, help = "use the cache") #cmdLineParser.add_option("-f", action="store", type="string", dest="file", default="", help="the input file") cmdLineParser.add_argument("-p", "--port", action="store", type=int, dest="port", default=4005, help="The TCP port to use") args = cmdLineParser.parse_args() print("Using args", args) import logging logging.debug("Using args %s", args) #print(args) logging.debug("now is %s", datetime.datetime.now()) logging.getLogger().setLevel(logging.ERROR) #enable logging when member vars are assigned import utils from order import Order Order.__setattr__ = utils.setattr_log from contract import Contract, DeltaNeutralContract Contract.__setattr__ = utils.setattr_log DeltaNeutralContract.__setattr__ = utils.setattr_log from tag_value import TagValue TagValue.__setattr__ = utils.setattr_log TimeCondition.__setattr__ = utils.setattr_log ExecutionCondition.__setattr__ = utils.setattr_log MarginCondition.__setattr__ = utils.setattr_log PriceCondition.__setattr__ = utils.setattr_log PercentChangeCondition.__setattr__ = utils.setattr_log VolumeCondition.__setattr__ = utils.setattr_log #from inspect import signature as sig #import code; code.interact(local=dict(globals(), **locals())) #sys.exit(1) app = TestApp() app.connect("127.0.0.1", args.port, 0) app.reqCurrentTime() app.reqManagedAccts() app.reqAccountSummary(reqId=2, groupName="All", tags="NetLiquidation") app.reqAllOpenOrders() contract = Contract() contract.symbol = "AMD" contract.secType = "STK" contract.currency = "USD" contract.exchange = "SMART" #app.reqMarketDataType(1) #app.reqMktData(1001, contract, "", snapshot=True) #app.cancelMktData(1001) #app.reqExecutions(2001, ExecutionFilter()) #app.reqContractDetails(3001, contract) #app.reqPositions() #app.reqIds(2) #app.reqMktDepth(4001, contract, 5, "") #app.cancelMktDepth(4001) #app.reqNewsBulletins(allMsgs=True) #app.cancelNewsBulletins() #app.requestFA(FaDataTypeEnum.GROUPS) #app.reqHistoricalData(5001, contract, "20161215 16:00:00", "2 D", # "1 hour", "TRADES", 0, 1, []) #app.cancelHistoricalData(5001) #app.reqFundamentalData(6001, contract, "ReportSnapshot") #app.cancelFundamentalData(6001) #app.queryDisplayGroups(7001) #app.subscribeToGroupEvents(7002, 1) #app.unsubscribeFromGroupEvents(7002) #app.reqScannerParameters() ss = ScannerSubscription() ss.instrument = "STK" ss.locationCode = "STK.US" ss.scanCode = "TOP_PERC_LOSE" #app.reqScannerSubscription(8001, ss, []) #app.cancelScannerSubscription(8001) #app.reqRealTimeBars(9001, contract, 5, "TRADES", 0, []) #app.cancelRealTimeBars(9001) #app.reqSecDefOptParams(10001, "AMD", "", "STK", 4391) #app.reqSoftDollarTiers(11001) #app.reqFamilyCodes() #app.reqMatchingSymbols(12001, "AMD") contract = Contract() contract.symbol = "AMD" contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20170120" contract.strike = 10 contract.right = "C" contract.multiplier = "100" #Often, contracts will also require a trading class to rule out ambiguities contract.tradingClass = "AMD" #app.calculateImpliedVolatility(13001, contract, 1.3, 10.85) #app.calculateOptionPrice(13002, contract, 0.65, 10.85) app.run()
def main(): house = House(1200, "Western Road", 2, True) contract = Contract("31-Dec-2016", 1200.00) rental = Rental(house, contract) print(rental)