def from_data(cls, data: dict) -> LazyGradedVestingAccount: data = data["value"] return cls( address=data["address"], coins=Coins.from_data(data["coins"]), public_key=PublicKey.from_data(data["public_key"]), account_number=data["account_number"], sequence=data["sequence"], original_vesting=Coins.from_data(data["original_vesting"]), delegated_free=Coins.from_data(data["delegated_free"]), delegated_vesting=Coins.from_data(data["delegated_vesting"]), end_time=data["end_time"], vesting_schedules=data["vesting_schedules"], )
async def validator_rewards(self, validator: ValAddress) -> ValidatorRewards: """Fetches the commission reward data for a validator. Args: validator (ValAddress): validator operator address Returns: ValidatorRewards: validator rewards """ res = await self._c._get(f"/distribution/validators/{validator}") return ValidatorRewards( self_bond_rewards=Coins.from_data(res["self_bond_rewards"]), val_commission=Coins.from_data(res["val_commission"]), )
def from_data(cls, data: dict) -> MsgDeposit: data = data["value"] return cls( proposal_id=data["proposal_id"], depositor=data["depositor"], amount=Coins.from_data(data["amount"]), )
def from_data(cls, data) -> AggregateExchangeRateVote: return cls( exchange_rate_tuples=Coins( [Coin(d.denom, d.exchange_rate) for d in data["exchange_rate_tuples"]], ), voter=data["voter"], )
def from_data(cls, data: dict) -> MsgSend: data = data["value"] return cls( from_address=data["from_address"], to_address=data["to_address"], amount=Coins.from_data(data["amount"]), )
async def community_pool(self) -> Coins: """Fetches the community pool. Returns: Coins: community pool """ res = await self._c._get("/distribution/community_pool") return Coins.from_data(res)
def from_data(cls, data: dict) -> CommunityPoolSpendProposal: data = data["value"] return cls( title=data["title"], description=data["description"], recipient=data["recipient"], amount=Coins.from_data(data["amount"]), )
async def tax_proceeds(self) -> Coins: """Fetches the current tax proceeds. Returns: Coins: tax proceeds """ res = await self._c._get("/treasury/tax_proceeds") return Coins.from_data(res)
def from_data(cls, data: dict) -> MsgAggregateExchangeRateVote: data = data["value"] return cls( exchange_rates=Coins.from_str(data["exchange_rates"]), salt=data["salt"], feeder=data["feeder"], validator=data["validator"], )
def from_data(cls, data: dict) -> MsgExecuteContract: data = data["value"] return cls( sender=data["sender"], contract=data["contract"], execute_msg=b64_to_dict(data["execute_msg"]), coins=Coins.from_data(data["coins"]), )
def test_clobbers_similar_denom(): coins1 = Coins([Coin("ukrw", 1000), Coin("uluna", 1000), Coin("uluna", 1000)]) coinKRW = coins1["ukrw"] coinLUNA = coins1["uluna"] assert coinKRW.amount == 1000 assert coinLUNA.amount == 2000
def from_data(cls, data: dict) -> MsgInstantiateContract: data = data["value"] return cls( owner=data["owner"], code_id=data["code_id"], init_msg=b64_to_dict(data["init_msg"]), init_coins=Coins.from_data(data["init_coins"]), migratable=data["migratable"], )
def from_data(cls, data: dict) -> Account: data = data["value"] return cls( address=data["address"], coins=Coins.from_data(data["coins"]), public_key=PublicKey.from_data(data["public_key"]), account_number=data["account_number"], sequence=data["sequence"], )
async def rewards(self, delegator: AccAddress) -> Rewards: """Fetches the staking reward data for a delegator. Args: delegator (AccAddress): delegator account address Returns: Rewards: delegator rewards """ res = await self._c._get( f"/distribution/delegators/{delegator}/rewards") return Rewards( rewards={ item["validator_address"]: Coins.from_data(item["reward"] or []) for item in res["rewards"] }, total=Coins.from_data(res["total"]), )
def from_data(cls, data: dict) -> MsgSubmitProposal: from terra_sdk.util.parse_content import parse_content data = data["value"] content = parse_content(data["content"]) return cls( content=content, initial_deposit=Coins.from_data(data["initial_deposit"]), proposer=data["proposer"], )
async def balance(self, address: AccAddress) -> Coins: """Fetches an account's current balance. Args: address (AccAddress): account address Returns: Coins: balance """ res = await self._c._get(f"/bank/balances/{address}") return Coins.from_data(res)
def from_data(cls, data: dict) -> Proposal: return cls( id=data["id"], content=Content.from_data(data["content"]), proposal_status=data["proposal_status"], final_tally_result=data["final_tally_result"], submit_time=data["submit_time"], deposit_end_time=data["deposit_end_time"], total_deposit=Coins.from_data(data["total_deposit"]), voting_start_time=data["voting_start_time"], voting_end_time=data["voting_end_time"], )
async def estimate_fee( self, tx: Union[StdSignMsg, StdTx], gas_prices: Optional[Coins.Input] = None, gas_adjustment: Optional[Numeric.Input] = None, denoms: Optional[List[str]] = None, ) -> StdFee: """Estimates the proper fee to apply by simulating it within the node. Args: tx (Union[StdSignMsg, StdTx]): transaction to estimate fee for gas_prices (Optional[Coins.Input], optional): gas prices to use. gas_adjustment (Optional[Numeric.Input], optional): gas adjustment to use. denoms (Optional[List[str]], optional): list of denoms to use to pay for gas. Returns: StdFee: estimated fee """ gas_prices = gas_prices or self._c.gas_prices gas_adjustment = gas_adjustment or self._c.gas_adjustment if isinstance(tx, StdSignMsg): tx_value = tx.to_stdtx().to_data()["value"] else: tx_value = tx.to_data()["value"] tx_value["fee"]["gas"] = "0" data = { "tx": tx_value, "gas_prices": gas_prices and Coins(gas_prices).to_data(), "gas_adjustment": gas_adjustment and str(gas_adjustment), } res = await self._c._post("/txs/estimate_fee", data) fees = Coins.from_data(res["fees"]) # only pick the denoms we are interested in? if denoms: fees = fees.filter(lambda c: c.denom in denoms) # type: ignore return StdFee(int(res["gas"]), fees)
async def main(): async with LocalTerra() as terra: test1 = terra.wallets["test1"] contract_file = open(Path(__file__).parent / "./contract.wasm", "rb") file_bytes = base64.b64encode(contract_file.read()).decode() store_code = MsgStoreCode(test1.key.acc_address, file_bytes) store_code_tx = await test1.create_and_sign_tx(msgs=[store_code]) store_code_tx_result = await terra.tx.broadcast(store_code_tx) print(store_code_tx_result) code_id = store_code_tx_result.logs[0].events_by_type["store_code"][ "code_id"][0] instantiate = MsgInstantiateContract( test1.key.acc_address, code_id, {"count": 0}, { "uluna": 10000000, "ukrw": 1000000 }, False, ) instantiate_tx = await test1.create_and_sign_tx(msgs=[instantiate]) instantiate_tx_result = await terra.tx.broadcast(instantiate_tx) print(instantiate_tx_result) contract_address = instantiate_tx_result.logs[0].events_by_type[ "instantiate_contract"]["contract_address"][0] execute = MsgExecuteContract( test1.key.acc_address, contract_address, {"increment": {}}, {"uluna": 100000}, ) execute_tx = await test1.create_and_sign_tx(msgs=[execute], fee=StdFee( 1000000, Coins(uluna=1000000))) execute_tx_result = await terra.tx.broadcast(execute_tx) print(execute_tx_result) result = await terra.wasm.contract_query(contract_address, {"get_count": {}}) print(result)
async def async_main(): async with AsyncLocalTerra() as terra: test1 = terra.wallets["test1"] store_code_tx = await test1.create_and_sign_tx( msgs=[ MsgStoreCode( test1.key.acc_address, read_file_as_b64(Path(__file__).parent / "./contract.wasm"), ) ] ) store_code_tx_result = await terra.tx.broadcast(store_code_tx) print(store_code_tx_result) code_id = get_code_id(store_code_tx_result) instantiate_tx = await test1.create_and_sign_tx( msgs=[ MsgInstantiateContract( test1.key.acc_address, code_id, {"count": 0}, {"uluna": 10000000, "ukrw": 1000000}, False, ) ] ) instantiate_tx_result = await terra.tx.broadcast(instantiate_tx) print(instantiate_tx_result) contract_address = get_contract_address(instantiate_tx_result) execute_tx = await test1.create_and_sign_tx( msgs=[ MsgExecuteContract( test1.key.acc_address, contract_address, {"increment": {}}, {"uluna": 100000}, ) ], fee=StdFee(1000000, Coins(uluna=1000000)), ) execute_tx_result = await terra.tx.broadcast(execute_tx) print(execute_tx_result) result = await terra.wasm.contract_query(contract_address, {"get_count": {}}) print(result)
def __init__( self, url: str, chain_id: Optional[str] = None, gas_prices: Optional[Coins.Input] = None, gas_adjustment: Optional[Numeric.Input] = None, loop: Optional[AbstractEventLoop] = None, _create_session: bool = True, # don't create a session (used for sync LCDClient) ): if loop is None: loop = get_event_loop() self.loop = loop if _create_session: self.session = ClientSession( headers={"Accept": "application/json"}, loop=self.loop) self.chain_id = chain_id self.url = url self.gas_prices = Coins(gas_prices) self.gas_adjustment = gas_adjustment self.last_request_height = None self.auth = AsyncAuthAPI(self) self.bank = AsyncBankAPI(self) self.distribution = AsyncDistributionAPI(self) self.gov = AsyncGovAPI(self) self.market = AsyncMarketAPI(self) self.mint = AsyncMintAPI(self) self.msgauth = AsyncMsgAuthAPI(self) self.oracle = AsyncOracleAPI(self) self.slashing = AsyncSlashingAPI(self) self.staking = AsyncStakingAPI(self) self.supply = AsyncSupplyAPI(self) self.tendermint = AsyncTendermintAPI(self) self.treasury = AsyncTreasuryAPI(self) self.wasm = AsyncWasmAPI(self) self.tx = AsyncTxAPI(self)
def test_from_str(): int_coins_string = "5ukrw,12uluna" dec_coins_string = "2.3ukrw,1.45uluna" neg_dec_coins_string = "-1.0ukrw,2.5uluna" int_coins = Coins(ukrw=5, uluna="12") dec_coins = Coins( ukrw=2.3, uluna="1.45", ) neg_dec_coins = Coins( ukrw="-1.0", uluna=2.5, ) assert Coins.from_str(int_coins_string) == int_coins assert Coins.from_str(dec_coins_string) == dec_coins assert Coins.from_str(neg_dec_coins_string) == neg_dec_coins
async def balance(self, address: AccAddress) -> Coins: res = await self._c._get(f"/bank/balances/{address}") return Coins.from_data(res)
def from_data(cls, data: dict) -> SendAuthorization: data = data["value"] return cls(spend_limit=Coins.from_data(data["spend_limit"]))
async def exchange_rates(self) -> Coins: res = self._c._get(f"/oracle/denoms/exchange_rates", raw=True) if res.get("result"): return Coins.from_data(res) else: return Coins({})
def test_rejects_nonhomogenous_sets(): with pytest.raises(TypeError) as e: Coins(uluna=1000, ukrw=1.234)
async def tax_proceeds(self) -> Coins: res = await self._c._get(f"/treasury/tax_proceeds") return Coins.from_data(res)
def from_data(cls, data: dict) -> MsgFundCommunityPool: data = data["value"] return cls(depositor=data["depositor"], amount=Coins.from_data(data["amount"]))