def test_reserved_name(self): print("1. delegate reserved name 1") (r_owner_1_pk, r_owner_1_pu) = ts4.make_keypair() # can be also r_owner_1 = ts4.BaseContract('TestReservedNamesOwner', dict(), pubkey=r_owner_1_pu, private_key=r_owner_1_pk, nickname='r_owner_1') # Start name regsitration process # function regName(address dens, string name, uint32 nic_name_years, uint128 bid_value) self.r_owner.call_method( 'regReservedName', dict(name=s2b(self.r_name_1), nic_name_years=1, name_owner=r_owner_1.address(), name_owner_key=r_owner_1_pu)) ts4.dispatch_messages() r_nic_addr = self.creator.call_getter('resolve', dict(name=s2b(self.r_name_1))) r_nic = ts4.BaseContract('NIC', ctor_params=None, address=r_nic_addr) # check second address is the winner self.assertEqual(int(r_owner_1_pu, 16), r_nic.call_getter('m_name_owner_key')) self.assertEqual(self.now + year_seconds, r_nic.call_getter('m_owns_until'))
def test_second_bidder_owns_test_name(self): bid_seed = 54 bid_value = 12 * ton (b2_pk, b2_pu) = ts4.make_keypair() bidder2 = ts4.BaseContract('TestAuctionBidder', dict(bid_key=b2_pu, seed=bid_seed), pubkey=b2_pu, private_key=b2_pk, nickname='bidder2') # Start name regsitration process # function regName(address dens, string name, uint32 nic_name_years, uint128 bid_value) bidder2.call_method( 'regName', dict(dens=self.creator.address(), name=self.name, nic_name_years=self.nic_years, bid_value=bid_value)) ts4.dispatch_messages() auction_addr = self.creator.call_getter('resolveAuctionAddress', dict(name=self.name)) # auction collect phase self.inc_now(7 * DAY_SEC + 1) # function payBid(uint256 bid_key, uint128 bid_value, uint32 seed bidder2.call_method('payBid', dict(auction=auction_addr, bid_value=12 * ton)) self.bidder.call_method('payBid', dict(auction=auction_addr, bid_value=10 * ton)) ts4.dispatch_messages() # after collect phase self.inc_now(DAY_SEC + 1) bidder2.call_method('updateAuctionState', dict(auction=auction_addr)) ts4.dispatch_messages() # get nic address nic_address = self.creator.call_getter('resolve', dict(name=self.name)) nic_test_name = ts4.BaseContract('NIC', ctor_params=None, address=nic_address) # check second address is the winner self.assertEqual(int(b2_pu, 16), nic_test_name.call_getter('m_name_owner_key')) self.assertEqual(self.now + year_seconds, nic_test_name.call_getter('m_owns_until')) # check not winning bidder will receive bid funds back self.assertEqual(10 * ts4.GRAM, self.bidder.call_getter('m_last_received')) self.assertEqual(auction_addr, self.bidder.call_getter('m_last_from'))
def test3(): print('Transfer with flags') # Deploy the sender's contract and register nickname to be used in the output sender = ts4.BaseContract('tutorial09', {}, nickname='Sender') balance_sender = sender.balance # Deploy the another one recipient's contract and register nickname to be used in the output recipient = ts4.BaseContract('tutorial09', {}, nickname='Recipient') addr_recipient = recipient.address balance_recipient = recipient.balance # Send grams to the recipient (regular transfer) amount = 3 * ts4.GRAM params = dict(addr=addr_recipient, amount=amount, flags=0) sender.call_method('send_grams_with_flags', params) # Dispatch created message ts4.dispatch_one_message() # Сheck the current balance of the sender and recipient sender.ensure_balance(balance_sender - amount) recipient.ensure_balance(balance_recipient + amount) # Send remainig balance and self-destroy sender's contract params = dict(addr=addr_recipient, amount=0, flags=160) sender.call_method('send_grams_with_flags', params) ts4.dispatch_one_message() # Сheck the current balance of the recipient, it's should be increased by sender's balance recipient.ensure_balance(balance_recipient + balance_sender) # Balance of the sender should be None, because of the contract destroyed assert eq(None, ts4.get_balance(sender.address))
def test2(): print('Transfer with payload') # Deploy the sender's contract and register nickname to be used in the output sender = ts4.BaseContract('tutorial09', {}, nickname='Sender') balance_sender = sender.balance # Deploy the another one recipient's contract and register nickname to be used in the output recipient = ts4.BaseContract('tutorial09', {}, nickname='Recipient') addr_recipient = recipient.address balance_recipient = recipient.balance # Send grams to the recipient without payload amount = 2 * ts4.GRAM comment = 'some comment' params = dict(addr=addr_recipient, amount=amount, comment=ts4.str2bytes(comment)) sender.call_method('send_grams_with_payload', params) # Dispatch created message ts4.dispatch_one_message() # Сheck the current balance of the sender and recipient sender.ensure_balance(balance_sender - amount) recipient.ensure_balance(balance_recipient + amount) # Pick up event that was created by called method of the called contract event = ts4.pop_event() decoded = recipient.decode_event(event) # Check correctness of the received data assert eq(comment, decoded.comment) assert eq(amount, decoded.amount)
def setUpClass(cls): (cls.root_pk, cls.root_pu) = ts4.make_keypair() cls.set_now(int(time.time())) # 1 min cls.name_str = 'test_name' cls.name = ts4.str2bytes(cls.name_str) cls.nic_name_timespan = 100 # string name, TvmCell nic_code, uint32 owns_until, uint256 name_owner_key, address name_owner_address cls.code = ts4.core.load_code_cell(os.environ['OUT_PATH'] + '/Auction.tvc') cls.creator = ts4.BaseContract('TestAuctionCreator', dict(), nickname='root', pubkey=cls.root_pu, private_key=cls.root_pk) bid_seed = 34 bid_value = 10 * ts4.GRAM (bid_pk, cls.bid_pu) = ts4.make_keypair() cls.bidder = ts4.BaseContract('TestAuctionBidder', dict(bid_key=cls.bid_pu, seed=bid_seed), pubkey=cls.bid_pu, private_key=bid_pk) # Dispatch unprocessed messages to actually construct a second contract # function deployAuction(string name, TvmCell code, uint32 nic_name_timespan, uint32 nic_name_starts_at, uint32 bid_phase_ends_at, uint32 ends_at, uint256 bid_key, uint256 bid_hash) public { cls.creator.call_method( 'deployAuction', dict(name=cls.name, code=cls.code, nic_name_timespan=cls.nic_name_timespan, nic_name_starts_at=cls.now + cls.nic_name_timespan, bid_phase_ends_at=cls.now + cls.nic_name_timespan - 40, ends_at=cls.now + cls.nic_name_timespan, bid_key=cls.bid_pu, bid_value=bid_value, bid_seed=bid_seed)) cls.addr = cls.creator.call_getter('m_address') ts4.ensure_address(cls.addr) ts4.register_nickname(cls.addr, 'auction') print('Deploying test_name auction at {}'.format(cls.addr)) ts4.dispatch_messages() # At this point NIC_test_name is deployed at a known address, # so we create a wrapper to access it cls.auction = ts4.BaseContract('Auction', ctor_params=None, address=cls.addr)
def setUpClass(cls): (cls.owner_pk, cls.owner_pu) = ts4.make_keypair() (cls.root_pk, cls.root_pu) = ts4.make_keypair() cls.set_now(int(time.time())) # 1 min cls.own_timespan = 60 cls.owns_until = cls.now + cls.own_timespan cls.name = ts4.str2bytes('test_name') cls.owner = ts4.BaseContract('TestNICOwner', dict(), nickname='owner', pubkey=cls.owner_pu, private_key=cls.owner_pk) ts4.ensure_address(cls.owner.address()) # string name, TvmCell nic_code, uint32 owns_until, uint256 name_owner_key, address name_owner_address cls.nic_code = ts4.core.load_code_cell(os.environ['OUT_PATH'] + '/NIC.tvc') cls.creator = ts4.BaseContract('TestNICCreator', dict(), nickname='root', pubkey=cls.root_pu, private_key=cls.root_pk) # Dispatch unprocessed messages to actually construct a second contract cls.creator.call_method( 'deployNic', dict(name=cls.name, nic_code=cls.nic_code, owns_until=cls.owns_until, name_owner_key=cls.owner_pu, name_owner_address=cls.owner.address())) cls.nic_addr = cls.creator.call_getter('m_nic_address') ts4.register_nickname(cls.nic_addr, 'test_name_nic') cls.owner.call_method('set_nic_address', dict(nic_address=cls.nic_addr)) print('Deploying test_name nic at {}'.format(cls.nic_addr)) ts4.dispatch_messages() # print("hash('name') = ", cls.creator.call_getter("stringHash", {"s": s2b("name")}) ) # At this point NIC_test_name is deployed at a known address, # so we create a wrapper to access it cls.nic_test_name = ts4.BaseContract('NIC', ctor_params=None, address=cls.nic_addr)
def setUpClass(cls): (cls.root_pk, cls.root_pu) = ts4.make_keypair() cls.set_now(int(time.time())) # 1 min cls.name_str = 'test_name' cls.name = ts4.str2bytes(cls.name_str) cls.nic_years = 1 # string name, TvmCell nic_code, uint32 owns_until, uint256 name_owner_key, address name_owner_address cls.auction_code = ts4.core.load_code_cell(os.environ['OUT_PATH'] + '/Auction.tvc') cls.nic_code = ts4.core.load_code_cell(os.environ['OUT_PATH'] + '/NIC.tvc') (cls.r_owner_pk, cls.r_owner_pu) = ts4.make_keypair() cls.r_owner = ts4.BaseContract('TestReservedNamesOwner', dict(), nickname = 'r_owner', pubkey = cls.r_owner_pu, private_key= cls.r_owner_pk) cls.r_name_1 = 'reserved_name_1' cls.r_name_2 = 'reserved_name_2' # constructor(TvmCell nic_code, TvmCell auction_code, address reserved_names_owner, string[] reserved_names) public { cls.creator = ts4.BaseContract('DeNSRoot', dict( nic_code = cls.nic_code, auction_code = cls.auction_code, # no reserved names used reserved_names_owner = cls.r_owner.address(), reserved_names = [s2b(cls.r_name_1),s2b(cls.r_name_1)] ), nickname = 'root', pubkey = cls.root_pu, private_key= cls.root_pk) cls.r_owner.call_method('set_m_dens_addr', dict(dens_addr = cls.creator.address())) ts4.dispatch_messages() # after 10 sec cls.inc_now(10) # first bidder bid_seed = 34 bid_value = 10 * ton (bid_pk, cls.bid_pu) = ts4.make_keypair() cls.bidder = ts4.BaseContract('TestAuctionBidder', dict(bid_key = cls.bid_pu, seed = bid_seed), pubkey=cls.bid_pu, private_key=bid_pk, nickname = 'bidder') # Start name regsitration process # function regName(address dens, string name. uint32 nic_name_years, uint128 bid_value) public cls.bidder.call_method('regName', dict( dens = cls.creator.address(), name = cls.name, nic_name_years = cls.nic_years, bid_value = bid_value)) ts4.dispatch_messages()
def test1(): # Deploy a contract. Constructor is called automatically. tut = ts4.BaseContract('tutorial03_1', {}) # Call a getter and ensure that we received correct integer value expected_value = 3735928559 assert eq(expected_value, tut.call_getter('m_number'))
def test3(): t_number = 3054 # Deploy a contract with calling constructor (offchain) tut = ts4.BaseContract('tutorial03_2', ctor_params={'t_number': t_number}) # Call a getter and ensure that we received correct integer value assert eq(t_number, tut.call_getter('m_number'))
def test2(): t_number = 12648430 # Deploy a contract without construction tut = ts4.BaseContract('tutorial03_2', ctor_params=None) # And construct it manually with an external message tut.call_method('constructor', {'t_number': t_number}) # Call a getter and ensure that we received correct integer value assert eq(t_number, tut.call_getter('m_number'))
def test4(): (private_key, public_key) = ts4.make_keypair() t_number = 14613198 # Deploy a contract with given (by pubkey) owner. # Private key is needed here only when constructor checks # that message is signed. tut = ts4.BaseContract('tutorial03_3', ctor_params=dict(t_number=t_number), pubkey=public_key, private_key=private_key) assert eq(t_number, tut.call_getter('m_number'))
def test_exchanger(self): ts4.reset_all() # reset all data ts4.init('./', verbose=True) key1 = ts4.make_keypair() self.public1 = key1[1] self.secret1 = key1[0] now = int(time.time()) ts4.core.set_now(now) test = ts4.BaseContract('test', dict(), pubkey=self.public, private_key=self.secret, balance=150_000_000_000, nickname="test") now += 5 ts4.core.set_now(now) main = ts4.BaseContract('main', dict(), pubkey=self.public, private_key=self.secret, balance=150_000_000_000, nickname="main") now += 5 ts4.core.set_now(now) test.call_method("change_address", dict(_adr=main.addr), private_key=self.secret) now += 5 ts4.core.set_now(now) test.call_method("createTimer", dict(_payload=1, _time=20), private_key=self.secret) while len(ts4.globals.QUEUE) > 0: now += 5 ts4.core.set_now(now) ts4.dispatch_one_message() print(test.call_getter("results"))
def test4(): # Generating a pair of keys keypair = ts4.make_keypair() t_number = 14613198 # Deploy a contract with given (by public key) owner. # Private key is needed here only when constructor checks # that message is signed. tut = ts4.BaseContract('tutorial03_3', ctor_params = dict(t_number = t_number), keypair = keypair ) # Check the validity of the key pair assert eq(keypair, tut.keypair) # Call a getter and ensure that we received correct integer value assert eq(t_number, tut.call_getter('m_number'))
def test1(): # Deploy a contract to virtual blockchain tut02 = ts4.BaseContract('tutorial02', {}) # Call method to set integer value t_number = 3735928559 tut02.call_method('set_number', {'value': t_number}) # Call a getter and ensure that we received correct integer value assert eq(t_number, tut02.call_getter('m_number')) # Call method to set address t_address = ts4.Address( '0:c4a31362f0dd98a8cc9282c2f19358c888dfce460d93adb395fa138d61ae5069') tut02.call_method('set_address', {'value': t_address}) assert eq(t_address, tut02.call_getter('m_address')) # Call method to set boolean value t_bool = True tut02.call_method('set_bool', {'value': t_bool}) assert eq(t_bool, tut02.call_getter('m_bool')) # Call method to set bytes value. In ABI `bytes` type is represented as a hex string t_bytes = ts4.Bytes('d090d091d092') tut02.call_method('set_bytes', {'value': t_bytes}) assert eq(t_bytes, tut02.call_getter('m_bytes')) # String values are represented in hex, so we need to use `str2bytes()` helper. t_string = 'coffeeАБВ' tut02.call_method('set_string', {'value': ts4.str2bytes(t_string)}) # Call the getter and ensure that we received correct string value. assert eq(t_string, tut02.call_getter('m_string')) # Call method to set array. t_array = [1, 2, 3, 4, 5] tut02.call_method('set_array', {'value': t_array}) assert eq(t_array, tut02.call_getter('m_array')) # Check using structures t_struct = dict(s_number=t_number, s_address=t_address, s_array=t_array) tut02.call_method('set_struct', {'someStruct': t_struct}) assert eq(t_struct, tut02.call_getter('get_struct'))
def init_smc_nft_root(owner, mintType=0, fee=0): smc = ts4.BaseContract( "NftRootCustomMint", { "mintType": mintType, "fee": fee, "name": "name", "descriprion": "descriprion", "icon": "", "addrAuthor": owner, }, initial_data={"_addrOwner": owner}, ) code_index = ts4.load_code_cell("Index") code_index_basis = ts4.load_code_cell("IndexBasis") code_data = ts4.load_code_cell("Data") code_data_chunk = ts4.load_code_cell("DataChunk") def setCode(method, code): call_with_wallet( smc_wallet, smc.address, 2 * 10**8, ts4.encode_message_body( "NftRootCustomMint", method, {"code": code}, ), ) ts4.dispatch_messages() setCode("setCodeIndex", code_index) setCode("setCodeIndexBasis", code_index_basis) setCode("setCodeData", code_data) setCode("setCodeDataChunk", code_data_chunk) assert smc.call_getter("_inited", {}) == True, "Contract hasn't been inited yet" return smc
def test_owner_change_before_expiration(self): (self.owner2_pk, self.owner2_pu) = ts4.make_keypair() self.owner2 = ts4.BaseContract('TestNICOwner', dict(), nickname='owner2', pubkey=self.owner2_pu, private_key=self.owner2_pk) ts4.dispatch_messages() self.set_now(self.owns_until - 10) # uint32 nic_name_timespan, uint256 owner_key, address owner_address, uint128 value self.creator.call_method( 'setNextOwner', dict(nic_name_timespan=self.own_timespan, owner_key=self.owner2_pu, owner_address=self.owner2.address())) ts4.dispatch_messages() # check owner not changed self.assertEqual(int(self.owner_pu, 16), self.nic_test_name.call_getter('m_name_owner_key')) self.assertEqual(self.owns_until, self.nic_test_name.call_getter('m_owns_until')) self.set_now(self.owns_until) # update nic state self.creator.call_method('updateState', dict()) ts4.dispatch_messages() # check owner changed self.assertEqual(int(self.owner2_pu, 16), self.nic_test_name.call_getter('m_name_owner_key')) self.assertEqual(self.owns_until + self.own_timespan, self.nic_test_name.call_getter('m_owns_until'))
def test_owner_change_at_expiration(self): (self.owner1_pk, self.owner1_pu) = ts4.make_keypair() self.owner1 = ts4.BaseContract('TestNICOwner', dict(), nickname='owner1', pubkey=self.owner1_pu, private_key=self.owner1_pk) ts4.dispatch_messages() self.set_now(self.owns_until) # update self.owns_until = self.owns_until + self.own_timespan print("now = ", self.now) balance_before = self.owner.balance() # uint32 nic_name_timespan, uint256 owner_key, address owner_address, uint128 value self.creator.call_method( 'setNextOwner', dict(nic_name_timespan=self.own_timespan, owner_key=self.owner1_pu, owner_address=self.owner1.address())) ts4.dispatch_messages() # check owner changed self.assertEqual(int(self.owner1_pu, 16), self.nic_test_name.call_getter('m_name_owner_key')) self.assertEqual(self.owns_until, self.nic_test_name.call_getter('m_owns_until')) # check prev owner become the value self.assertEqual(balance_before + 10 * 1000000000, self.owner.balance())
def test_earlier_bid_wins(self): seed2 = 54 (b2_pk, b2_pu) = ts4.make_keypair() bidder2 = ts4.BaseContract('TestAuctionBidder', dict(bid_key=b2_pu, seed=seed2), pubkey=b2_pu, private_key=b2_pk) seed3 = 42 (b3_pk, b3_pu) = ts4.make_keypair() bidder3 = ts4.BaseContract('TestAuctionBidder', dict(bid_key=b3_pu, seed=seed3), pubkey=b3_pu, private_key=b3_pk) # function bid(uint256 bid_hash) external onlyExtMessage onlySigned onlyIfBidPhase { self.auction.call_method( 'bid', dict(bid_hash=hex( self.auction.call_getter( 'calculateBidHash', dict(bid_value=12 * ts4.GRAM, seed=54)))), private_key=b2_pk) ts4.dispatch_messages() # collect phase self.inc_now(self.nic_name_timespan - 39) # payBid(address auction, uint128 bid_value) public bidder2.call_method('payBid', dict(auction=self.addr, bid_value=12 * ts4.GRAM)) self.inc_now(1) ts4.dispatch_messages() bidder3.call_method('payBid', dict(auction=self.addr, bid_value=12 * ts4.GRAM)) self.inc_now(1) ts4.dispatch_messages() self.bidder.call_method( 'payBid', dict(auction=self.addr, bid_value=10 * ts4.GRAM)) self.inc_now(1) ts4.dispatch_messages() # after collect phase self.inc_now(40) self.auction.call_method('updateState', dict()) ts4.dispatch_messages() # check second address is the winner self.assertEqual(10 * ts4.GRAM, self.creator.call_getter('m_win_price')) self.assertEqual(bidder2.address(), self.creator.call_getter('m_win_address')) self.assertEqual(int(b2_pu, 16), self.creator.call_getter('m_win_key')) # check not winning bidder will receive bid funds back self.assertEqual(10 * ts4.GRAM, self.bidder.call_getter('m_last_received')) self.assertEqual(self.auction.address(), self.bidder.call_getter('m_last_from')) self.assertEqual(12 * ts4.GRAM, bidder3.call_getter('m_last_received')) self.assertEqual(self.auction.address(), bidder3.call_getter('m_last_from'))
root = Root() seg('Code installation') root.call_method_signed('installPlatform', {'code': plat}) root.call_method_signed('installCertificate', {'code': cert}) root.call_method_signed('installAuction', {'code': auct}) root.call_method_signed('installBid', {'code': bid}) seg('Upgrade (setCode)') root.call_method_signed('upgrade', {'code': rcod}) seg('Create test accounts') tac, tad = {}, {} for i in range(1, 9 + 1): tac[i] = ts4.BaseContract('DensTest', {'_root': root.address()}, nickname='Test{}'.format(i), override_address=ts4.Address('0:' + (64 * str(i)))) tad[i] = tac[i].addr() seg('Directly deploy some domains') root.call_method_signed('directlyDeploy', { 'name': h('test1'), '_owner': tad[1], 'expiry': bt + 1000 }) root.call_method_signed('directlyDeploy', { 'name': h('test2'), '_owner': tad[2], 'expiry': bt + 20000 }) root.call_method_signed('directlyDeploy', {
eq = ts4.eq # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info ts4.init('contracts/', verbose=True) # Load code and data of the second contract code = ts4.load_code_cell('tutorial05_2.tvc') data = ts4.load_data_cell('tutorial05_2.tvc') # Register ABI of the second contract in the system beforehand ts4.register_abi('tutorial05_2') # Deploy the first contract and register nickname to be used in the output contract1 = ts4.BaseContract('tutorial05_1', dict(code=code, data=data), nickname='Parent') zero_address = ts4.Address('0:' + '0' * 64) assert eq(zero_address, contract1.call_getter('m_address')) # Ask contract1 to deploy contract2 with a given key contract1.call_method('deploy', dict(key=123)) # Fetch the address of the contract to be deployed address2 = contract1.call_getter('m_address') ts4.ensure_address(address2) # We register nickname for this contract so see it in the verbose output ts4.register_nickname(address2, 'Child')
''' import tonos_ts4.ts4 as ts4 eq = ts4.eq # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info ts4.init('contracts/', verbose = False) # Load a contract from .tvc-file and deploy it into a virtual blockchain. # Constructor is called automatically. # After deployment, "logstr: Constructor" will appear in the output to facilitate the debugging process. tut01 = ts4.BaseContract('tutorial01', {}) # Call an integer getter and ensure that we received correct value print("Fetching 'm_number'... ", end='') expected_value = 3735928559 assert eq(expected_value, tut01.call_getter('m_number')) print('ok') # Call the getter and ensure that we received correct address print("Fetching 'm_address'... ", end='') expected_address = ts4.Address('0:c4a31362f0dd98a8cc9282c2f19358c888dfce460d93adb395fa138d61ae5069') assert eq(expected_address, tut01.call_getter('m_address')) print('ok') # Call the getter and ensure that we received correct boolean value print("Fetching 'm_bool'... ", end='')
setCode("setCodeIndex", code_index) setCode("setCodeIndexBasis", code_index_basis) setCode("setCodeData", code_data) setCode("setCodeDataChunk", code_data_chunk) assert smc.call_getter("_inited", {}) == True, "Contract hasn't been inited yet" return smc keys_multisig = ts4.make_keypair() smc_wallet = ts4.BaseContract( "SurfMultisigWallet", { "owners": [keys_multisig[1]], "reqConfirms": 1 }, keypair=keys_multisig, ) smc_wallet_random = ts4.BaseContract( "SurfMultisigWallet", { "owners": [keys_multisig[1]], "reqConfirms": 1 }, keypair=keys_multisig, ) # Test only owner minting smc_nft_root = init_smc_nft_root(smc_wallet.address, 0, 0)
def test1(): print('Transfer with bounce') # Deploy the sender's contract and register nickname to be used in the output sender = ts4.BaseContract('tutorial09', {}, nickname='Sender') addr_sender = sender.address balance_sender = 100 * ts4.GRAM # Сheck the sender's initial balance. There are 100 grams by default sender.ensure_balance(balance_sender) # The contract address of the recipient addr_recipient = ts4.Address( '0:c4a31362f0dd98a8cc9282c2f19358c888dfce460d93adb395fa138d61ae5069') # Register nickname to be used in the output ts4.register_nickname(addr_recipient, 'Recipient1') # Сheck the recipient's balance. Until is not deployed it has no balance assert eq(None, ts4.get_balance(addr_recipient)) # Send grams to the recipient with bounce flag amount = ts4.GRAM params = dict(addr=addr_recipient, amount=amount, bounce=True) sender.call_method('send_grams', params) # Pick up internal message that was created by `send_grams()` call msg_transfer = ts4.peek_msg() assert eq(addr_sender, msg_transfer.src) assert eq(addr_recipient, msg_transfer.dst) assert eq(amount, msg_transfer.value) # Dispatch created message ts4.dispatch_one_message() # Сheck the sender's current balance sender.ensure_balance(balance_sender - amount) # Pick up internal message that was bounced msg_bounced = ts4.peek_msg() assert eq(addr_recipient, msg_bounced.src) assert eq(addr_sender, msg_bounced.dst) assert eq(amount, msg_bounced.value) assert eq(True, msg_bounced.bounced) # Dispatch bounced message ts4.dispatch_one_message() # Balance of the recipient should stay empty assert eq(None, ts4.get_balance(addr_recipient)) print('Transfer without bounce') # Send grams to the recipient without bounce flag params = dict(addr=addr_recipient, amount=amount, bounce=False) sender.call_method('send_grams', params) # Dispatch created message ts4.dispatch_one_message() # Check balance of the recipient, it should be equal to transferred amount assert eq(amount, ts4.get_balance(addr_recipient)) # Сhecking the sender's balance, it should be decreased by the amount of the transfer sender.ensure_balance(balance_sender - amount)
''' import tonos_ts4.ts4 as ts4 eq = ts4.eq # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info ts4.init('contracts/', verbose = True) default_balance = 100*ts4.GRAM # Deploy the sender's contract and register nickname to be used in the output tut09 = ts4.BaseContract('tutorial09', {}, nickname = 'Sender') addr_sender = tut09.address() # Сheck the sender's initial balance. There are 100 grams by default tut09.ensure_balance(default_balance) # The contract address of the recipient addr_recipient = ts4.Address('0:c4a31362f0dd98a8cc9282c2f19358c888dfce460d93adb395fa138d61ae5069') # Register nickname to be used in the output ts4.register_nickname(addr_recipient, 'Recipient') # Сheck the recipient's balance. Until is not deployed it has no balance assert eq(None, ts4.get_balance(addr_recipient)) # Send grams to the recipient with bounce flag
''' This tutorial demonstrates how to encode a payload for use in a transfer function call ''' from tonos_ts4 import ts4 eq = ts4.eq # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info ts4.init('contracts/', verbose=True) # Deploy a contract (encoder/sender) sender = ts4.BaseContract('tutorial10_1', {}) # Register nickname to be used in the output ts4.register_nickname(sender.address, 'Sender') # Deploy a contract (receiver) receiver = ts4.BaseContract('tutorial10_2', {}) ts4.register_nickname(receiver.address, 'Receiver') # Ensure that current value in the receiver contract is default assert eq(0, receiver.call_getter('m_value')) value = 0xbeaf # Encode calling of the receiver contract payload = sender.call_getter('encode', {'value': value})
def test_second_bidder_owns_test_name(self): print("1. first auction second bid") bid_seed = 54 bid_value = 12 * ton (b2_pk, b2_pu) = ts4.make_keypair() bidder2 = ts4.BaseContract('TestAuctionBidder', dict(bid_key=b2_pu, seed=bid_seed), pubkey=b2_pu, private_key=b2_pk, nickname='bidder2') # Start name regsitration process # function regName(address dens, string name, uint32 nic_name_years, uint128 bid_value) bidder2.call_method( 'regName', dict(dens=self.creator.address(), name=self.name, nic_name_years=self.nic_years, bid_value=bid_value)) ts4.dispatch_messages() auction_addr = self.creator.call_getter('resolveAuctionAddress', dict(name=self.name)) auction = ts4.BaseContract('Auction', ctor_params=None, address=auction_addr) print(auction.call_getter('getAuctionInfo')) # auction collect phase self.inc_now(7 * DAY_SEC + 1) # function payBid(uint256 bid_key, uint128 bid_value, uint32 seed print("2. first auction bidder2 pays auction price 12") bidder2.call_method('payBid', dict(auction=auction_addr, bid_value=bid_value)) print("3. first auction bidder1 pays auction price 10") self.bidder.call_method('payBid', dict(auction=auction_addr, bid_value=10 * ton)) ts4.dispatch_messages() # after collect phase self.inc_now(DAY_SEC + 1) print("4. first auction bidder2 updates auction") bidder2.call_method('updateAuctionState', dict(auction=auction_addr)) # auction in completed state at this point ts4.dispatch_messages() self.inc_now(10) # get nic for test_name nic_address = self.creator.call_getter('resolve', dict(name=self.name)) nic_test_name = ts4.BaseContract('NIC', ctor_params=None, address=nic_address) owns_until = nic_test_name.call_getter('m_owns_until') print("5. first auction bidder2 owns name for ", owns_until) bid3_seed = 34 bid3_value = 22 * ton (b3_pk, b3_pu) = ts4.make_keypair() self.set_now(owns_until - (28 * DAY_SEC) - 2) bidder3 = ts4.BaseContract('TestAuctionBidder', dict(bid_key=b3_pu, seed=bid3_seed), pubkey=b3_pu, private_key=b3_pk, nickname='bidder3') print("6. auction bidder3 will try to register name") # should cause 312 error by message dispatching with self.assertRaises(Exception): bidder3.call_method( 'regName', dict(dens=self.creator.address(), name=self.name, nic_name_years=self.nic_years, bid_value=bid_value)) ts4.dispatch_messages() print(auction.call_getter('getAuctionInfo')) self.set_now(owns_until - (28 * DAY_SEC)) print("7. name registration opened") print("8. bidder2 will try to register name") bidder2.call_method( 'regName', dict(dens=self.creator.address(), name=self.name, nic_name_years=self.nic_years, bid_value=bid_value)) print(auction.call_getter('getAuctionInfo')) ts4.dispatch_messages() # shift to the auction collect phase self.inc_now(7 * DAY_SEC + 1) print("9. bidder3 will try to pay for name") bidder3.call_method('payBid', dict(auction=auction_addr, bid_value=bid3_value)) print("10. bidder2 will try to pay for name") bidder2.call_method('payBid', dict(auction=auction_addr, bid_value=12 * ton)) ts4.dispatch_messages() print("11. shift auction to the after collect") self.inc_now(DAY_SEC + 1) print("12. first auction bidder2 updates auction") bidder2.call_method('updateAuctionState', dict(auction=auction_addr)) # auction in completed state at this point ts4.dispatch_messages() print("13. move to the new owner NIC period") self.set_now(owns_until + 1) # update nic state bidder2.call_method('updateNICState', dict(nic=nic_address)) ts4.dispatch_messages() # check second address is the winner self.assertEqual(int(b2_pu, 16), nic_test_name.call_getter('m_name_owner_key')) self.assertEqual(owns_until + year_seconds, nic_test_name.call_getter('m_owns_until'))
''' This script demonstrate how to exploit the droneContract smart contract. ''' import tonos_ts4.ts4 as ts4 # Set a directory where the artifacts of the used contracts are located ts4.set_tests_path('') # Toggle to print additional execution info ts4.set_verbose(False) #Load the contract dron = ts4.BaseContract('droneContract', {}) class dron(ts4.BaseContract): def __init__(self): self.create_keypair() # We pass a public key to the constructor that will identify the contract owner super(dron, self).__init__('droneContract', {}, pubkey=self.public_key_) # Create a method to call setNumber without the owner's signature def setNumber(self, value, expect_ec=0): return self.call_method('setNumber', {'value': value}, expect_ec=expect_ec) # Create a method to call setNumber with the owner's signature
This tutorial shows you how to check the balance of accounts with different states. ''' import tonos_ts4.ts4 as ts4 eq = ts4.eq # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info ts4.init('contracts/', verbose=True) # The address of a non-existing contract empty_account = ts4.Address( '0:c4a31362f0dd98a8cc9282c2f19358c888dfce460d93adb395fa138d61ae5069') # Check balance of non-existing address assert eq(None, ts4.get_balance(empty_account)) default_balance = 100 * ts4.GRAM # Deploy the contract tut08 = ts4.BaseContract('tutorial08', {}) # Сheck balance of the deployed contract. There are 100 grams by default tut08.ensure_balance(default_balance) # Another way to check the balance of contract assert eq(default_balance, tut08.balance())
def test(): voters_set = [int(l, 16) for l in open('../hash-list').readlines()] constructor_params = {'voters_set': voters_set, 'num_options': 2} AnonymousVote = ts4.BaseContract('AnonymousVote', constructor_params, keypair=ts4.make_keypair()) proof = ts4.Bytes(open('../proof', 'rb').read().hex()) AnonymousVote.call_method( 'vote', { 'proof': proof, 'vote_choice': 0, 'signed_vote': 0xE7EA50574F6E21467915257BC3BFA4B1B7315BF2E29F9DD6F5E53C9B99595A51, 'anonymous_id': 0xFCEFE3D2B1EEFC9A506B167151E81AE248F31DE896AD48DC6DCC5F4805373B5A }) assert AnonymousVote.call_getter('get_results') == {0: 1} assert AnonymousVote.call_getter( 'get_vote', { 'anonymous_id': 0xFCEFE3D2B1EEFC9A506B167151E81AE248F31DE896AD48DC6DCC5F4805373B5A }) == (True, 0) assert AnonymousVote.call_getter( 'get_vote', { 'anonymous_id': 0x03028200952785FA92B6925F22270C139E3BDD3CC0A9EACF39B5987AFB531039 }) == (False, 0) proof2 = ts4.Bytes(open('../proof2', 'rb').read().hex()) AnonymousVote.call_method( 'vote', { 'proof': proof2, 'vote_choice': 0, 'signed_vote': 0x03040B9229613FB97333325A055681A7A0942C36354C63A1861693174D4FDC16, 'anonymous_id': 0x03028200952785FA92B6925F22270C139E3BDD3CC0A9EACF39B5987AFB531039 }) assert AnonymousVote.call_getter('get_results') == {0: 2} assert AnonymousVote.call_getter( 'get_vote', { 'anonymous_id': 0xFCEFE3D2B1EEFC9A506B167151E81AE248F31DE896AD48DC6DCC5F4805373B5A }) == (True, 0) assert AnonymousVote.call_getter( 'get_vote', { 'anonymous_id': 0x03028200952785FA92B6925F22270C139E3BDD3CC0A9EACF39B5987AFB531039 }) == (True, 0) AnonymousVote.call_method('vote', { 'proof': proof, 'vote_choice': 0, 'signed_vote': 0xE7EA50574F6E21467915257BC3BFA4B1B7315BF2E29F9DD6F5E53C9B99595A51, 'anonymous_id': 0xFCEFE3D2B1EEFC9A506B167151E81AE248F31DE896AD48DC6DCC5F4805373B5A }, expect_ec=109) assert AnonymousVote.call_getter('get_results') == {0: 2} print('Ok')
ts4.pop_event() # Processing last event msg_event = ts4.pop_event() # Ensure that dst address is empty (one more variant) assert msg_event.is_event('ReceivedReply', src = neighbor1, dst = ts4.Address(None)) assert eq(t_value, int(msg_event.params['reply'])) # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info ts4.init('contracts/', verbose = True) # Deploy contracts contract1 = ts4.BaseContract('tutorial04_1', {}) neighbor1 = contract1.addr() contract2 = ts4.BaseContract('tutorial04_2', {}) neighbor2 = contract2.addr() # Register nicknames to be used in the output ts4.register_nickname(neighbor1, 'Alice') ts4.register_nickname(neighbor2, 'Bob') print('Contract 1 deployed at {}'.format(neighbor1)) print('Contract 2 deployed at {}'.format(neighbor2)) test1() # Ensure we have no undispatched messages ts4.ensure_queue_empty()