test.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. # python3 -m pip install pycryptodomex uvarint pyteal web3 coincurve
  2. import sys
  3. sys.path.append("..")
  4. from admin import PortalCore, Account
  5. from gentest import GenTest
  6. from base64 import b64decode
  7. from typing import List, Tuple, Dict, Any, Optional, Union
  8. import base64
  9. import random
  10. import time
  11. import hashlib
  12. import uuid
  13. import json
  14. from algosdk.v2client.algod import AlgodClient
  15. from algosdk.kmd import KMDClient
  16. from algosdk import account, mnemonic
  17. from algosdk.encoding import decode_address, encode_address
  18. from algosdk.future import transaction
  19. from pyteal import compileTeal, Mode, Expr
  20. from pyteal import *
  21. from algosdk.logic import get_application_address
  22. from vaa_verify import get_vaa_verify
  23. from algosdk.future.transaction import LogicSig
  24. from test_contract import get_test_app
  25. from algosdk.v2client import indexer
  26. import pprint
  27. class AlgoTest(PortalCore):
  28. def __init__(self) -> None:
  29. super().__init__()
  30. def getBalances(self, client: AlgodClient, account: str) -> Dict[int, int]:
  31. balances: Dict[int, int] = dict()
  32. accountInfo = client.account_info(account)
  33. # set key 0 to Algo balance
  34. balances[0] = accountInfo["amount"]
  35. assets: List[Dict[str, Any]] = accountInfo.get("assets", [])
  36. for assetHolding in assets:
  37. assetID = assetHolding["asset-id"]
  38. amount = assetHolding["amount"]
  39. balances[assetID] = amount
  40. return balances
  41. def createTestApp(
  42. self,
  43. client: AlgodClient,
  44. sender: Account,
  45. ) -> int:
  46. approval, clear = get_test_app(client)
  47. globalSchema = transaction.StateSchema(num_uints=4, num_byte_slices=30)
  48. localSchema = transaction.StateSchema(num_uints=0, num_byte_slices=16)
  49. app_args = []
  50. txn = transaction.ApplicationCreateTxn(
  51. sender=sender.getAddress(),
  52. on_complete=transaction.OnComplete.NoOpOC,
  53. approval_program=b64decode(approval["result"]),
  54. clear_program=b64decode(clear["result"]),
  55. global_schema=globalSchema,
  56. local_schema=localSchema,
  57. app_args=app_args,
  58. sp=client.suggested_params(),
  59. )
  60. signedTxn = txn.sign(sender.getPrivateKey())
  61. client.send_transaction(signedTxn)
  62. response = self.waitForTransaction(client, signedTxn.get_txid())
  63. assert response.applicationIndex is not None and response.applicationIndex > 0
  64. txn = transaction.PaymentTxn(sender = sender.getAddress(), sp = client.suggested_params(),
  65. receiver = get_application_address(response.applicationIndex), amt = 300000)
  66. signedTxn = txn.sign(sender.getPrivateKey())
  67. client.send_transaction(signedTxn)
  68. return response.applicationIndex
  69. def parseSeqFromLog(self, txn):
  70. try:
  71. return int.from_bytes(b64decode(txn.innerTxns[-1]["logs"][0]), "big")
  72. except Exception as err:
  73. pprint.pprint(txn.__dict__)
  74. raise
  75. def getVAA(self, client, sender, sid, app):
  76. if sid == None:
  77. raise Exception("getVAA called with a sid of None")
  78. saddr = get_application_address(app)
  79. # SOOO, we send a nop txn through to push the block forward
  80. # one
  81. # This is ONLY needed on a local net... the indexer will sit
  82. # on the last block for 30 to 60 seconds... we don't want this
  83. # log in prod since it is wasteful of gas
  84. if (self.INDEXER_ROUND > 512 and not self.args.testnet): # until they fix it
  85. print("indexer is broken in local net... stop/clean/restart the sandbox")
  86. sys.exit(0)
  87. txns = []
  88. txns.append(
  89. transaction.ApplicationCallTxn(
  90. sender=sender.getAddress(),
  91. index=self.tokenid,
  92. on_complete=transaction.OnComplete.NoOpOC,
  93. app_args=[b"nop"],
  94. sp=client.suggested_params(),
  95. )
  96. )
  97. self.sendTxn(client, sender, txns, False)
  98. if self.myindexer == None:
  99. print("indexer address: " + self.INDEXER_ADDRESS)
  100. self.myindexer = indexer.IndexerClient(indexer_token=self.INDEXER_TOKEN, indexer_address=self.INDEXER_ADDRESS)
  101. while True:
  102. nexttoken = ""
  103. while True:
  104. response = self.myindexer.search_transactions( min_round=self.INDEXER_ROUND, note_prefix=self.NOTE_PREFIX, next_page=nexttoken)
  105. # pprint.pprint(response)
  106. for x in response["transactions"]:
  107. # pprint.pprint(x)
  108. for y in x["inner-txns"]:
  109. if "application-transaction" not in y:
  110. continue
  111. if y["application-transaction"]["application-id"] != self.coreid:
  112. continue
  113. if len(y["logs"]) == 0:
  114. continue
  115. args = y["application-transaction"]["application-args"]
  116. if len(args) < 2:
  117. continue
  118. if base64.b64decode(args[0]) != b'publishMessage':
  119. continue
  120. seq = int.from_bytes(base64.b64decode(y["logs"][0]), "big")
  121. if seq != sid:
  122. continue
  123. if y["sender"] != saddr:
  124. continue;
  125. emitter = decode_address(y["sender"])
  126. payload = base64.b64decode(args[1])
  127. # pprint.pprint([seq, y["sender"], payload.hex()])
  128. # sys.exit(0)
  129. return self.gt.genVaa(emitter, seq, payload)
  130. if 'next-token' in response:
  131. nexttoken = response['next-token']
  132. else:
  133. self.INDEXER_ROUND = response['current-round'] + 1
  134. break
  135. time.sleep(1)
  136. def publishMessage(self, client, sender, vaa, appid):
  137. aa = decode_address(get_application_address(appid)).hex()
  138. emitter_addr = self.optin(client, sender, self.coreid, 0, aa)
  139. txns = []
  140. sp = client.suggested_params()
  141. a = transaction.ApplicationCallTxn(
  142. sender=sender.getAddress(),
  143. index=appid,
  144. on_complete=transaction.OnComplete.NoOpOC,
  145. app_args=[b"test1", vaa, self.coreid],
  146. foreign_apps = [self.coreid],
  147. accounts=[emitter_addr],
  148. sp=sp
  149. )
  150. a.fee = a.fee * 2
  151. txns.append(a)
  152. resp = self.sendTxn(client, sender, txns, True)
  153. self.INDEXER_ROUND = resp.confirmedRound
  154. return self.parseSeqFromLog(resp)
  155. def createTestAsset(self, client, sender):
  156. txns = []
  157. a = transaction.PaymentTxn(
  158. sender = sender.getAddress(),
  159. sp = client.suggested_params(),
  160. receiver = get_application_address(self.testid),
  161. amt = 300000
  162. )
  163. txns.append(a)
  164. sp = client.suggested_params()
  165. a = transaction.ApplicationCallTxn(
  166. sender=sender.getAddress(),
  167. index=self.testid,
  168. on_complete=transaction.OnComplete.NoOpOC,
  169. app_args=[b"setup"],
  170. sp=sp
  171. )
  172. a.fee = a.fee * 2
  173. txns.append(a)
  174. transaction.assign_group_id(txns)
  175. grp = []
  176. pk = sender.getPrivateKey()
  177. for t in txns:
  178. grp.append(t.sign(pk))
  179. client.send_transactions(grp)
  180. resp = self.waitForTransaction(client, grp[-1].get_txid())
  181. aid = int.from_bytes(resp.__dict__["logs"][0], "big")
  182. print("Opting " + sender.getAddress() + " into " + str(aid))
  183. self.asset_optin(client, sender, aid, sender.getAddress())
  184. txns = []
  185. a = transaction.ApplicationCallTxn(
  186. sender=sender.getAddress(),
  187. index=self.testid,
  188. on_complete=transaction.OnComplete.NoOpOC,
  189. app_args=[b"mint"],
  190. foreign_assets = [aid],
  191. sp=sp
  192. )
  193. a.fee = a.fee * 2
  194. txns.append(a)
  195. resp = self.sendTxn(client, sender, txns, True)
  196. # self.INDEXER_ROUND = resp.confirmedRound
  197. return aid
  198. def getCreator(self, client, sender, asset_id):
  199. return client.asset_info(asset_id)["params"]["creator"]
  200. def testAttest(self, client, sender, asset_id):
  201. taddr = get_application_address(self.tokenid)
  202. aa = decode_address(taddr).hex()
  203. emitter_addr = self.optin(client, sender, self.coreid, 0, aa)
  204. if asset_id != 0:
  205. creator = self.getCreator(client, sender, asset_id)
  206. c = client.account_info(creator)
  207. wormhole = c.get("auth-addr") == taddr
  208. else:
  209. c = None
  210. wormhole = False
  211. if not wormhole:
  212. creator = self.optin(client, sender, self.tokenid, asset_id, b"native".hex())
  213. txns = []
  214. sp = client.suggested_params()
  215. txns.append(transaction.ApplicationCallTxn(
  216. sender=sender.getAddress(),
  217. index=self.tokenid,
  218. on_complete=transaction.OnComplete.NoOpOC,
  219. app_args=[b"nop"],
  220. sp=sp
  221. ))
  222. mfee = self.getMessageFee()
  223. if (mfee > 0):
  224. txns.append(transaction.PaymentTxn(sender = sender.getAddress(), sp = sp, receiver = get_application_address(self.tokenid), amt = mfee))
  225. accts = [emitter_addr, creator, get_application_address(self.coreid)]
  226. if c != None:
  227. accts.append(c["address"])
  228. a = transaction.ApplicationCallTxn(
  229. sender=sender.getAddress(),
  230. index=self.tokenid,
  231. on_complete=transaction.OnComplete.NoOpOC,
  232. app_args=[b"attestToken", asset_id],
  233. foreign_apps = [self.coreid],
  234. foreign_assets = [asset_id],
  235. accounts=accts,
  236. sp=sp
  237. )
  238. if (mfee > 0):
  239. a.fee = a.fee * 3
  240. else:
  241. a.fee = a.fee * 2
  242. txns.append(a)
  243. resp = self.sendTxn(client, sender, txns, True)
  244. # Point us at the correct round
  245. self.INDEXER_ROUND = resp.confirmedRound
  246. # print(encode_address(resp.__dict__["logs"][0]))
  247. # print(encode_address(resp.__dict__["logs"][1]))
  248. # pprint.pprint(resp.__dict__)
  249. return self.parseSeqFromLog(resp)
  250. def transferFromAlgorand(self, client, sender, asset_id, quantity, receiver, chain, fee, payload = None):
  251. # pprint.pprint(["transferFromAlgorand", asset_id, quantity, receiver, chain, fee])
  252. taddr = get_application_address(self.tokenid)
  253. aa = decode_address(taddr).hex()
  254. emitter_addr = self.optin(client, sender, self.coreid, 0, aa)
  255. # asset_id 0 is ALGO
  256. if asset_id == 0:
  257. wormhole = False
  258. else:
  259. creator = self.getCreator(client, sender, asset_id)
  260. c = client.account_info(creator)
  261. wormhole = c.get("auth-addr") == taddr
  262. txns = []
  263. mfee = self.getMessageFee()
  264. if (mfee > 0):
  265. txns.append(transaction.PaymentTxn(sender = sender.getAddress(), sp = sp, receiver = get_application_address(self.tokenid), amt = mfee))
  266. if not wormhole:
  267. creator = self.optin(client, sender, self.tokenid, asset_id, b"native".hex())
  268. print("non wormhole account " + creator)
  269. sp = client.suggested_params()
  270. if (asset_id != 0) and (not self.asset_optin_check(client, sender, asset_id, creator)):
  271. print("Looks like we need to optin")
  272. txns.append(
  273. transaction.PaymentTxn(
  274. sender=sender.getAddress(),
  275. receiver=creator,
  276. amt=100000,
  277. sp=sp
  278. )
  279. )
  280. # The tokenid app needs to do the optin since it has signature authority
  281. a = transaction.ApplicationCallTxn(
  282. sender=sender.getAddress(),
  283. index=self.tokenid,
  284. on_complete=transaction.OnComplete.NoOpOC,
  285. app_args=[b"optin", asset_id],
  286. foreign_assets = [asset_id],
  287. accounts=[creator],
  288. sp=sp
  289. )
  290. a.fee = a.fee * 2
  291. txns.append(a)
  292. self.sendTxn(client, sender, txns, False)
  293. txns = []
  294. txns.insert(0,
  295. transaction.ApplicationCallTxn(
  296. sender=sender.getAddress(),
  297. index=self.tokenid,
  298. on_complete=transaction.OnComplete.NoOpOC,
  299. app_args=[b"nop"],
  300. sp=client.suggested_params(),
  301. )
  302. )
  303. if asset_id == 0:
  304. print("asset_id == 0")
  305. txns.append(transaction.PaymentTxn(
  306. sender=sender.getAddress(),
  307. receiver=creator,
  308. amt=quantity,
  309. sp=sp,
  310. ))
  311. accounts=[emitter_addr, creator, creator]
  312. else:
  313. print("asset_id != 0")
  314. txns.append(
  315. transaction.AssetTransferTxn(
  316. sender = sender.getAddress(),
  317. sp = sp,
  318. receiver = creator,
  319. amt = quantity,
  320. index = asset_id
  321. ))
  322. accounts=[emitter_addr, creator, c["address"]]
  323. args = [b"sendTransfer", asset_id, quantity, decode_address(receiver), chain, fee]
  324. if None != payload:
  325. args.append(payload)
  326. #pprint.pprint(args)
  327. # print(self.tokenid)
  328. a = transaction.ApplicationCallTxn(
  329. sender=sender.getAddress(),
  330. index=self.tokenid,
  331. on_complete=transaction.OnComplete.NoOpOC,
  332. app_args=args,
  333. foreign_apps = [self.coreid],
  334. foreign_assets = [asset_id],
  335. accounts=accounts,
  336. sp=sp
  337. )
  338. a.fee = a.fee * 2
  339. txns.append(a)
  340. resp = self.sendTxn(client, sender, txns, True)
  341. self.INDEXER_ROUND = resp.confirmedRound
  342. # pprint.pprint([self.coreid, self.tokenid, resp.__dict__,
  343. # int.from_bytes(resp.__dict__["logs"][1], "big"),
  344. # int.from_bytes(resp.__dict__["logs"][2], "big"),
  345. # int.from_bytes(resp.__dict__["logs"][3], "big"),
  346. # int.from_bytes(resp.__dict__["logs"][4], "big"),
  347. # int.from_bytes(resp.__dict__["logs"][5], "big")
  348. # ])
  349. # print(encode_address(resp.__dict__["logs"][0]))
  350. # print(encode_address(resp.__dict__["logs"][1]))
  351. return self.parseSeqFromLog(resp)
  352. def asset_optin_check(self, client, sender, asset, receiver):
  353. if receiver not in self.asset_cache:
  354. self.asset_cache[receiver] = {}
  355. if asset in self.asset_cache[receiver]:
  356. return True
  357. ai = client.account_info(receiver)
  358. if "assets" in ai:
  359. for x in ai["assets"]:
  360. if x["asset-id"] == asset:
  361. self.asset_cache[receiver][asset] = True
  362. return True
  363. return False
  364. def asset_optin(self, client, sender, asset, receiver):
  365. if self.asset_optin_check(client, sender, asset, receiver):
  366. return
  367. pprint.pprint(["asset_optin", asset, receiver])
  368. sp = client.suggested_params()
  369. optin_txn = transaction.AssetTransferTxn(
  370. sender = sender.getAddress(),
  371. sp = sp,
  372. receiver = receiver,
  373. amt = 0,
  374. index = asset
  375. )
  376. transaction.assign_group_id([optin_txn])
  377. signed_optin = optin_txn.sign(sender.getPrivateKey())
  378. client.send_transactions([signed_optin])
  379. resp = self.waitForTransaction(client, signed_optin.get_txid())
  380. assert self.asset_optin_check(client, sender, asset, receiver), "The optin failed"
  381. print("woah! optin succeeded")
  382. def simple_test(self):
  383. # q = bytes.fromhex(gt.genAssetMeta(gt.guardianPrivKeys, 1, 1, 1, bytes.fromhex("4523c3F29447d1f32AEa95BEBD00383c4640F1b4"), 1, 8, b"USDC", b"CircleCoin"))
  384. # pprint.pprint(self.parseVAA(q))
  385. # sys.exit(0)
  386. # vaa = self.parseVAA(bytes.fromhex("0100000001010001ca2fbf60ac6227d47dda4fe2e7bccc087f27d22170a212b9800da5b4cbf0d64c52deb2f65ce58be2267bf5b366437c267b5c7b795cd6cea1ac2fee8a1db3ad006225f801000000010001000000000000000000000000000000000000000000000000000000000000000400000000000000012000000000000000000000000000000000000000000000000000000000436f72650200000000000001beFA429d57cD18b7F8A4d91A2da9AB4AF05d0FBe"))
  387. # pprint.pprint(vaa)
  388. # vaa = self.parseVAA(bytes.fromhex("01000000010100c22ce0a3c995fca993cb0e91af74d745b6ec1a04b3adf0bb3e432746b3e2ab5e635b65d34d5148726cac10e84bf5932a7f21b9545c362bd512617aa980e0fbf40062607566000000010001000000000000000000000000000000000000000000000000000000000000000400000000000000012000000000000000000000000000000000000000000000000000000000436f72650200000000000101beFA429d57cD18b7F8A4d91A2da9AB4AF05d0FBe"))
  389. # pprint.pprint(vaa)
  390. # sys.exit(0)
  391. gt = GenTest(True)
  392. self.gt = gt
  393. self.setup_args()
  394. if self.args.testnet:
  395. self.testnet()
  396. client = self.client = self.getAlgodClient()
  397. self.genTeal()
  398. self.vaa_verify = self.client.compile(get_vaa_verify())
  399. self.vaa_verify["lsig"] = LogicSig(base64.b64decode(self.vaa_verify["result"]))
  400. vaaLogs = []
  401. args = self.args
  402. if self.args.mnemonic:
  403. self.foundation = Account.FromMnemonic(self.args.mnemonic)
  404. if self.foundation == None:
  405. print("Generating the foundation account...")
  406. self.foundation = self.getTemporaryAccount(self.client)
  407. if self.foundation == None:
  408. print("We dont have a account? ")
  409. sys.exit(0)
  410. foundation = self.foundation
  411. seq = int(time.time())
  412. print("Creating the PortalCore app")
  413. self.coreid = self.createPortalCoreApp(client=client, sender=foundation)
  414. print("coreid = " + str(self.coreid) + " " + get_application_address(self.coreid))
  415. print("bootstrapping the guardian set...")
  416. bootVAA = bytes.fromhex(gt.genGuardianSetUpgrade(gt.guardianPrivKeys, 1, 1, seq, seq))
  417. self.bootGuardians(bootVAA, client, foundation, self.coreid)
  418. seq += 1
  419. print("grabbing a untrusted account")
  420. player = self.getTemporaryAccount(client)
  421. print(player.getAddress())
  422. print("")
  423. bal = self.getBalances(client, player.getAddress())
  424. pprint.pprint(bal)
  425. print("upgrading the the guardian set using untrusted account...")
  426. upgradeVAA = bytes.fromhex(gt.genGuardianSetUpgrade(gt.guardianPrivKeys, 1, 2, seq, seq))
  427. vaaLogs.append(["guardianUpgrade", upgradeVAA.hex()])
  428. self.submitVAA(upgradeVAA, client, player, self.coreid)
  429. bal = self.getBalances(client, player.getAddress())
  430. pprint.pprint(bal)
  431. seq += 1
  432. print("Create the token bridge")
  433. self.tokenid = self.createTokenBridgeApp(client, foundation)
  434. print("token bridge " + str(self.tokenid) + " address " + get_application_address(self.tokenid))
  435. ret = self.devnetUpgradeVAA()
  436. # pprint.pprint(ret)
  437. print("Submitting core")
  438. self.submitVAA(bytes.fromhex(ret[0]), self.client, foundation, self.coreid)
  439. print("Submitting token")
  440. self.submitVAA(bytes.fromhex(ret[1]), self.client, foundation, self.tokenid)
  441. print("successfully sent upgrade requests")
  442. for r in range(1, 6):
  443. print("Registering chain " + str(r))
  444. v = gt.genRegisterChain(gt.guardianPrivKeys, 2, seq, seq, r)
  445. vaa = bytes.fromhex(v)
  446. # pprint.pprint((v, self.parseVAA(vaa)))
  447. if r == 2:
  448. vaaLogs.append(["registerChain", v])
  449. self.submitVAA(vaa, client, player, self.tokenid)
  450. seq += 1
  451. bal = self.getBalances(client, player.getAddress())
  452. pprint.pprint(bal)
  453. print("Create a asset")
  454. attestVAA = bytes.fromhex(gt.genAssetMeta(gt.guardianPrivKeys, 2, seq, seq, bytes.fromhex("4523c3F29447d1f32AEa95BEBD00383c4640F1b4"), 1, 8, b"USDC", b"CircleCoin"))
  455. # paul - createWrappedOnAlgorand
  456. vaaLogs.append(["createWrappedOnAlgorand", attestVAA.hex()])
  457. self.submitVAA(attestVAA, client, player, self.tokenid)
  458. seq += 1
  459. p = self.parseVAA(attestVAA)
  460. chain_addr = self.optin(client, player, self.tokenid, p["FromChain"], p["Contract"])
  461. print("Create the same asset " + str(seq))
  462. # paul - updateWrappedOnAlgorand
  463. attestVAA = bytes.fromhex(gt.genAssetMeta(gt.guardianPrivKeys, 2, seq, seq, bytes.fromhex("4523c3F29447d1f32AEa95BEBD00383c4640F1b4"), 1, 8, b"USD2C", b"Circle2Coin"))
  464. self.submitVAA(attestVAA, client, player, self.tokenid)
  465. seq += 1
  466. print("Transfer the asset " + str(seq))
  467. transferVAA = bytes.fromhex(gt.genTransfer(gt.guardianPrivKeys, 1, 1, 1, 1, bytes.fromhex("4523c3F29447d1f32AEa95BEBD00383c4640F1b4"), 1, decode_address(player.getAddress()), 8, 0))
  468. # paul - redeemOnAlgorand
  469. vaaLogs.append(["redeemOnAlgorand", transferVAA.hex()])
  470. self.submitVAA(transferVAA, client, player, self.tokenid)
  471. seq += 1
  472. aid = client.account_info(player.getAddress())["assets"][0]["asset-id"]
  473. print("generate an attest of the asset we just received: " + str(aid))
  474. # paul - attestFromAlgorand
  475. self.testAttest(client, player, aid)
  476. print("Create the test app we will use to torture ourselves using a new player")
  477. player2 = self.getTemporaryAccount(client)
  478. print("player2 address " + player2.getAddress())
  479. player3 = self.getTemporaryAccount(client)
  480. print("player3 address " + player3.getAddress())
  481. self.testid = self.createTestApp(client, player2)
  482. print("testid " + str(self.testid) + " address " + get_application_address(self.testid))
  483. print("Sending a message payload to the core contract")
  484. sid = self.publishMessage(client, player, b"you also suck", self.testid)
  485. self.publishMessage(client, player2, b"second suck", self.testid)
  486. self.publishMessage(client, player3, b"last message", self.testid)
  487. print("Lets create a brand new non-wormhole asset and try to attest and send it out")
  488. self.testasset = self.createTestAsset(client, player2)
  489. print("test asset id: " + str(self.testasset))
  490. print("Now lets create an attest of ALGO")
  491. sid = self.testAttest(client, player2, 0)
  492. vaa = self.getVAA(client, player, sid, self.tokenid)
  493. v = self.parseVAA(bytes.fromhex(vaa))
  494. print("We got a " + v["Meta"])
  495. print("Lets try to create an attest for a non-wormhole thing with a huge number of decimals")
  496. # paul - attestFromAlgorand
  497. sid = self.testAttest(client, player2, self.testasset)
  498. print("... track down the generated VAA")
  499. vaa = self.getVAA(client, player, sid, self.tokenid)
  500. v = self.parseVAA(bytes.fromhex(vaa))
  501. print("We got a " + v["Meta"])
  502. pprint.pprint(self.getBalances(client, player.getAddress()))
  503. pprint.pprint(self.getBalances(client, player2.getAddress()))
  504. pprint.pprint(self.getBalances(client, player3.getAddress()))
  505. print("Lets transfer that asset to one of our other accounts... first lets create the vaa")
  506. # paul - transferFromAlgorand
  507. sid = self.transferFromAlgorand(client, player2, self.testasset, 100, player3.getAddress(), 8, 0)
  508. print("... track down the generated VAA")
  509. vaa = self.getVAA(client, player, sid, self.tokenid)
  510. print(".. and lets pass that to player3")
  511. vaaLogs.append(["transferFromAlgorand", vaa])
  512. #pprint.pprint(vaaLogs)
  513. self.submitVAA(bytes.fromhex(vaa), client, player3, self.tokenid)
  514. pprint.pprint(["player", self.getBalances(client, player.getAddress())])
  515. pprint.pprint(["player2", self.getBalances(client, player2.getAddress())])
  516. pprint.pprint(["player3", self.getBalances(client, player3.getAddress())])
  517. # Lets split it into two parts... the payload and the fee
  518. print("Lets split it into two parts... the payload and the fee (400 should go to player, 600 should go to player3)")
  519. sid = self.transferFromAlgorand(client, player2, self.testasset, 1000, player3.getAddress(), 8, 400)
  520. print("... track down the generated VAA")
  521. vaa = self.getVAA(client, player, sid, self.tokenid)
  522. # pprint.pprint(self.parseVAA(bytes.fromhex(vaa)))
  523. print(".. and lets pass that to player3 with fees being passed to player acting as a relayer (" + str(self.tokenid) + ")")
  524. self.submitVAA(bytes.fromhex(vaa), client, player, self.tokenid)
  525. pprint.pprint(["player", self.getBalances(client, player.getAddress())])
  526. pprint.pprint(["player2", self.getBalances(client, player2.getAddress())])
  527. pprint.pprint(["player3", self.getBalances(client, player3.getAddress())])
  528. # sys.exit(0)
  529. # Now it gets tricky, lets create a virgin account...
  530. pk, addr = account.generate_account()
  531. emptyAccount = Account(pk)
  532. print("How much is in the empty account? (" + addr + ")")
  533. pprint.pprint(self.getBalances(client, emptyAccount.getAddress()))
  534. # paul - transferFromAlgorand
  535. print("Lets transfer algo this time.... first lets create the vaa")
  536. sid = self.transferFromAlgorand(client, player2, 0, 1000000, emptyAccount.getAddress(), 8, 0)
  537. print("... track down the generated VAA")
  538. vaa = self.getVAA(client, player, sid, self.tokenid)
  539. # pprint.pprint(vaa)
  540. print(".. and lets pass that to the empty account.. but use somebody else to relay since we cannot pay for it")
  541. # paul - redeemOnAlgorand
  542. self.submitVAA(bytes.fromhex(vaa), client, player, self.tokenid)
  543. print("=================================================")
  544. print("How much is in the source account now?")
  545. pprint.pprint(self.getBalances(client, player2.getAddress()))
  546. print("How much is in the empty account now?")
  547. pprint.pprint(self.getBalances(client, emptyAccount.getAddress()))
  548. print("How much is in the player3 account now?")
  549. pprint.pprint(self.getBalances(client, player3.getAddress()))
  550. print("Lets transfer more algo.. split 40/60 with the relayer.. going to player3")
  551. sid = self.transferFromAlgorand(client, player2, 0, 1000000, player3.getAddress(), 8, 400000)
  552. print("... track down the generated VAA")
  553. vaa = self.getVAA(client, player, sid, self.tokenid)
  554. print(".. and lets pass that to player3.. but use the previously empty account to relay it")
  555. self.submitVAA(bytes.fromhex(vaa), client, emptyAccount, self.tokenid)
  556. print("How much is in the source account now?")
  557. pprint.pprint(self.getBalances(client, player2.getAddress()))
  558. print("How much is in the empty account now?")
  559. pprint.pprint(self.getBalances(client, emptyAccount.getAddress()))
  560. print("How much is in the player3 account now?")
  561. pprint.pprint(self.getBalances(client, player3.getAddress()))
  562. print("How about a payload3")
  563. sid = self.transferFromAlgorand(client, player2, 0, 100, get_application_address(self.testid), 8, 0, self.testid.to_bytes(8, "big")+b'hi mom')
  564. print("... track down the generated VAA")
  565. vaa = self.getVAA(client, player, sid, self.tokenid)
  566. print("testid balance before = ", self.getBalances(client, get_application_address(self.testid)))
  567. print(".. Lets let player3 relay it for us")
  568. self.submitVAA(bytes.fromhex(vaa), client, player3, self.tokenid)
  569. print("testid balance after = ", self.getBalances(client, get_application_address(self.testid)))
  570. print(".. Ok, now it is time to up the message fees")
  571. bal = self.getBalances(client, get_application_address(self.coreid))
  572. print("core contract has " + str(bal) + " algo (" + get_application_address(self.coreid) + ")")
  573. print("core contract has a MessageFee set to " + str(self.getMessageFee()))
  574. seq += 1
  575. v = gt.genGSetFee(gt.guardianPrivKeys, 2, seq, seq, 2000000)
  576. self.submitVAA(bytes.fromhex(v), client, player, self.coreid)
  577. seq += 1
  578. print("core contract now has a MessageFee set to " + str(self.getMessageFee()))
  579. # v = gt.genGSetFee(gt.guardianPrivKeys, 2, seq, seq, 0)
  580. # self.submitVAA(bytes.fromhex(v), client, player, self.coreid)
  581. # seq += 1
  582. # print("core contract is back to " + str(self.getMessageFee()))
  583. print("Generating an attest.. This will cause a message to get published .. which should cause fees to get sent to the core contract")
  584. sid = self.testAttest(client, player2, self.testasset)
  585. print("... track down the generated VAA")
  586. vaa = self.getVAA(client, player, sid, self.tokenid)
  587. v = self.parseVAA(bytes.fromhex(vaa))
  588. print("We got a " + v["Meta"])
  589. bal = self.getBalances(client, get_application_address(self.coreid))
  590. print("core contract has " + str(bal) + " algo (" + get_application_address(self.coreid) + ")")
  591. # print("player account: " + player.getAddress())
  592. # pprint.pprint(client.account_info(player.getAddress()))
  593. # print("player2 account: " + player2.getAddress())
  594. # pprint.pprint(client.account_info(player2.getAddress()))
  595. # print("foundation account: " + foundation.getAddress())
  596. # pprint.pprint(client.account_info(foundation.getAddress()))
  597. #
  598. # print("core app: " + get_application_address(self.coreid))
  599. # pprint.pprint(client.account_info(get_application_address(self.coreid))),
  600. #
  601. # print("token app: " + get_application_address(self.tokenid))
  602. # pprint.pprint(client.account_info(get_application_address(self.tokenid))),
  603. #
  604. # print("asset app: " + chain_addr)
  605. # pprint.pprint(client.account_info(chain_addr))
  606. if __name__ == "__main__":
  607. core = AlgoTest()
  608. core.simple_test()