Callum  Owen

Callum Owen

1650049020

What Is TERRA and UST? The Algorithmic Stablecoin Protocol Explained

Terra is a blockchain protocol underpinned by a suite of decentralized stablecoins. The most popular is called TerraUSD, or UST. The stablecoins maintain their pegs through a coin called LUNA. LUNA is a volatile cryptocurrency. The elasticity of its supply keeps the prices of its stablecoins in check

#terra #luna #blockchain #crypto 

What Is TERRA and UST? The Algorithmic Stablecoin Protocol Explained
黎 飞

黎 飞

1649934000

以太坊升级再次被推迟!Terra Luna价格将回升?

区块链分析公司Glassnode最新数据显示,目前比特币交易费用总额接近历史最低点。目前活跃实体的数量也就是类似于每日活跃用户仍然处于过去六年来建立的熊市通道内,交易数量也相对乏善可陈,目前每天约有22.5万笔交易,与2019年熊市期间的水平相似。此外在过去的两年中以太坊一直存在网络拥塞问题。即使是简单的以太坊交易,成本也可能高达5 美元,而在高峰时段的成本可能超过 100 美元。Binance Smart Chain和Solana等项目开始涌现,作为以太坊的替代方案,费用更低且交易吞吐量更高。尽管这些替代方案获得了巨大的人气和市值,但它们的速度是有代价的。也就是集中化问题。Binance Smart Chain只有21个验证器来确认交易,这使得它非常集中。

以太坊 2.0 已经拥有35.5万个验证器,使其成为迄今为止最去中心化的区块链。这两天以太坊合并领导人Tim Beiko在社交媒体上回应称以太坊合并不会在6月完成,但可能是之后的几个月。目前没有确定的日期,但他们肯定在以太坊PoW的最后阶段。随后他又补充称以太坊合并会在2022年内完成。至于此次PoW转PoS的合并升级的意义,只涉及到共识机制的改变,以太坊网络的可扩展性问题还需要依靠Layer2技术或分片链上线来解决。所以这次合并升级也不会降低以太坊主网高昂的Gas费,这个问题需要分片链与Layer2技术相结合才得以有效解决,即交易过程在便宜的第二层协议上执行,最终的状态交易数据库存储在分片链中。以太坊转向 PoS,用户通过质押以太币来保护网络的能力,预计将使网络的能源成本降低99%,并使以太坊更容易扩展。然而为以太坊建立一个新的共识机制会带来很大的复杂性。

除了引入一系列工程挑战外,以太坊的 PoS 模型还将添加一套新的博弈论机制,以确保网络验证者善意行事。传统投资者可能会发现,以太坊已经改变了游戏规则。以太坊正在发展成为一种交叉资产,具有独特的股权和商品以及货币特征。此前彭博分析师预估ETH的价值为 6128 美元,比当前水平上升了110%。虽然以太坊合并再次被推迟,但将以太坊从工作证明模式转变为权益证明模式,将以太坊转变为一种类似股权的工具,具有活力的供需动态,可能会推动市场对该资产的重大兴趣。以太坊在2021年产生了98亿美元的交易费用,比2020年增长了15倍,原因是DeFi和NFT 热潮爆发。该网络有望在 2022 年创收127亿美元增长 30% 。随着未来几个月合并前景的改善,以太坊可能会缩小估值差距,在 2022 年有可能超过其它资产。

另一方面在之前的视频中我们已经讨论过Twitter分析师0xHamz在一系列推文中声称Waves是加密领域最大的庞氏骗局,它以35%的利率借入USDC来购买自己的代币 WAVES,从而操纵了价格飙升,而WAVES 需要持续的市值增长来保持系统的稳定,这注定它最终将会崩溃,USDN也将脱钩。而我们说的Neutrino Dollar也就是USDN了,它是一种通过 Waves支持的Neutrino 协议发行的稳定币。目前Waves正处于两周以来的低点。有朋友好奇UST会不会像USDN也就是Waves的稳定币那样脱锚导致Luna 暴跌。UST不脱锚的核心来自于边际交易价格不低于1, 扣掉锁住的UST ,在外面流通的UST不过 30 亿枚,单日交易量10亿,即三分之一的换手率,支持不脱锚绰绰有余。

Luna Foundation Guard是作为算法稳定币 UST 的解析协议的实体,最近其钱包中又增加了1亿美元的比特币。LFG 的钱包现在包含 17 亿美元的 BTC和5.4984 亿美元的其他以美元计价的稳定币以及1474万美元的 Terra 。如果 Luna 实现其购买100亿美元比特币的目标,它将拥有仅次于 Binance冷钱包的第二大比特币钱包。Luna Foundation Guard简称也就是LFG,明面上的投资机构就有Jump Crypto和三箭资本以及Republic Capital等,整个生态基金的储备超过30亿美金,2个月前往Anchor储备池拨款就是4到5个亿,也撑起了Anchor 20%的超高年化。

此外Anchor是Terra整个生态内最为重要的生态位。因为这里锁了超过70%的UST,这就是UST最大的蓄水池。同时也因为20%的年化,被人各种诟病为庞氏骗局。Terra最早出来的时候,很多人都不知道他其实是一条Cosmos链,加上当时Cosmos生态不愠不火,也没人关心。Cosmos上一直没有稳定币,即没有USDT和USDC以及DAI,当时用Osmosis都只能卖成Atom。然后Terra开始反哺Cosmos,几个月前接入IBC,于是UST现在成了Cosmos整个生态最为重要的稳定币。Osmosis上唯一的稳定币就是UST,另一大生态Thorchain也在近期与Luna和UST集成完毕,如果你看好整个Cosmos生态,就得被迫看好UST。但有人会说Anchor 20%年化的问题。假设之后利率逐渐降低,部分存款人会退出,用 UST 换回真美元转为 Luna 砸盘。但这可以是分散和渐变的过程,最终是 UST 发行量坍缩从而导致Luna价格下跌,但不太可能不是瞬间崩盘。

最后据最新消息波卡DeFi平台Acala宣布与Terra生态固定利率协议Anchor Protocol达成合作,以提升Terra和波卡生态系统的去中心化稳定币空间。通过此次合作,Acala及其基于Kusama的平行链Karura将通过Liquid DOT和Liquid KSM帮助Anchor扩大UST稳定币的抵押品选项。Acala与Anchor还将专注于联合为Acala上的aUSD和UST提供高流动性池。这将成为UST用户进入波卡生态系统的门户。双方还将致力于在Acala和Terra生态系统中进行更多的集成和部署。此外波卡和Kusama网络的用户将能够在LKSM和LDOT的帮助下获得Anchor收益。实现这一目标的第一步是通过Wormhole转移他们的流动性质押资产到Terra。然后用户可以提供LDOT或LKSM作为抵押物在Anchor上借入UST。

#anchor #terra #acala #nft #eth 

以太坊升级再次被推迟!Terra Luna价格将回升?
黎 飞

黎 飞

1649666105

Waves被指控将崩盘?创始人Sasha Ivanov否认庞氏骗局?

Waves加密货币前几天再次达到了历史新高,一度逼近64美元为投资者带来了可观的回报。这可能受益于对美国推出Waves Labs的乐观情绪,但Twitter 上的言论表明,事实可能要黑暗得多。有分析师认为该项目为庞氏骗局,称其通过借用稳定币USDC 购买自己的代币并人为抬高 WAVES 的价格来实现近期收益。等一下我们将详细分享关于它的更多观点。之前的视频我们已经介绍过Waves于2016年推出,是一个支持各种用例的全球开源平台,包括 DApp和智能合约。它基于 PoS 共识,其原生代币是 WAVES。截至目前有近1.08亿枚 WAVES 代币在流通,而其最大供应量未知。Waves由乌克兰人Sasha Ivanov于2016 年创立,是一个无需许可的平台可轻松创建代币。自2016年年中推出以来,该代币已为投资者带来了超过12000%的回报,市值超过54亿美元。Waves代币是一种通缩代币,这意味着它的供应是无限的。

正如我们之前讨论的那样。价格飙升的原因一方面是因为2022年2月宣布迁移到Waves 2.0。在 Waves 2.0下将有一个新的通用治理模型。目的是提高每秒数千笔交易的高速度,并使网络更具适应性。然后美国公司Waves Labs 已加入合作伙伴网络。将为开发基于 Waves 的技术的美国团队设立 1.5 亿美元的基金和孵化计划,美国将成为 2022 年广泛采用的关键市场。其目标是引导价值 1.5 亿美元的资金来加速开发在其区块链上运行的去中心化应用程序项目和协议。这可能会引起人们对Waves网络的兴趣并促进其内部代币的使用。所以在接触它之前我们不能忘记Waves是乌克兰主导的加密货币,即其创始人是乌克兰出生的科学家,目前加密货币社区在正在进行的俄乌战争中受到亲乌克兰情绪的引导。
最近我看到了关于它的更多故事。Twitter分析师0xHamz在一系列推文中声称Waves是加密领域最大的庞氏骗局,它以35%的利率借入 USDC 来购买自己的代币 WAVES,从而操纵了价格飙升,而 WAVES 需要持续的市值增长来保持系统的稳定,这注定它最终将会崩溃,USDN也将脱钩。WAVES是Layer1 区块链,它的主要应用场景是用来铸造其原生稳定币USDN,可以将 WAVE与LUNA和MKR进行比较,而 USDN 就是对应的 UST和DAI。WAVES 的市值在两个月内增长了6倍,最初的催化剂是关于 WAVES是俄罗斯以太坊的说法,尽管关键绩效指标为 0,但它的表现远远超过以太坊。WAVES 需要增加市值,这样才能发行更多 USDN。所以了解它生态系统的健康状况的话,可以通过观察 WAVES与USDN 的市值之比,这个比率告诉我们可以发行多少 USDN。此外一旦该比率达到2.5倍,USDN 供应就会萎缩。WAVES 价格上涨就可以帮助 Waves不断提升发行 USDN 的能力。假设二者比率为最低目标的 2.5 倍,那 WAVES 就可以多发行13.8亿美元 USDN,同时在这个目标下USDN的收益率将达到5.4%,而AAVE的USDC和USDT 供应利率为3.5%。我们最近看到 USDN 以历史上最快的速度进行铸造,在过去4周内USDN 从4.75亿美元增长到8.75亿美元增长了85%,而 DAI 同期则是下降。

那么为什么会有人想持有 USDN呢?USDN由WAVES 提供支持,而 WAVES 的原生质押率为3.13%。所以USDN收益率等价于WAVES 原生质押率乘以支持率,也即目前 USDN 收益率为3.31%乘以6.60等于21.8%。但随着发行更多的 USDN,收益率将下降,为了保持发展势头WAVES 的市值需要持续增长,一旦支持率开始下降,USDN 的收益率就会下降。WAVES 团队是如何利用杠杆来制造大规模供应短缺的呢?详细流程分为几个步骤。首先在Vires上存入USDN。然后在 Vires 上借出 USDC。接着将USDC 转移到 Binance。紧接着使用USDC购买WAVE。再然后将WAVE 交易转换为USDN。如此操作并周而复始,这在链上是可以跟踪的。过去两个月,Vires 平台上的 USDC/USDT 的借款变得十分疯狂,借贷利率高于任何其他区块链网络上的利率。

Waves一直在借入 USDC或USDT,并兑换为 USDN。在整个过程中Waves必须吸引 USDC和USDT到Vires,从而借入新铸造的USDN。没有人会把钱借给用 USDN 抵押的人,因此 Waves 必须提供高于市场的价格来激励 USDC和USDT 存入该平台。没有硬通货存入等价于没有杠杆效应。WAVES 代币有 1 亿枚的供应总量,其中85%的WAVES 被抵押,只留下了约 1600 万枚的可交易WAVES 代币。交易所需要营运资金,一些持有人不会出售等等因素都需要考虑,我们假设这些在 1600 万枚的可交易WAVES 代币中占去了30%,那就又降为 1050 万枚,而当可交易供应只有10.5%时,就会很容易操纵市场的价格上限。Waves 可以在降到最低支持目标也就是2.5 倍的WAVES和USDN市值比之前,再发行 13.8 亿美元的 USDN,然后这 13.8 亿美元继续买入 1050 万枚的可交易WAVES,就意味着 Waves 可以将每枚 WAVES 推高到 131.43 美元,这就是波浪式庞氏骗局。它会先壮大然后萎缩。USDN 的发行最终据将逐渐减少,也就不再有目前程序化的 WAVES购买循环。而这意味着迅速的死亡,因为如果 WAVES 价格下跌足够多,那 WAVES 的市值可能低于待偿付的 USDN 市值,这将意味着 USDN 将资不抵债,并最终脱钩。如果 USDN 真的实质性脱钩,那 USDC在Vires 借贷平台上的空头可以清算 8.75 亿美元待偿付 USDN 中的 6.07 亿美元。

0xHamz认为这将是世界末日,所以他称这个平台为庞氏骗局,因为它是由借来的钱支撑起来的,没有有机活动。这种高交易量高价格的走势,诱使短线交易者在极小止损的情况下做多,而韩国交易所一直是 WAVES 的主要交易场所。确实WAVES 的价格增长受到可以铸造的 USDN 数量的限制。一旦 USDN 达到其限制,代币就会下跌,导致 USDN 最终失去与美元的1比1挂钩。在这种情况下主要受害者将是Vires上的USDC储户,因为没有流动性可以让他们提取资金。oxHamz 还指出WAVES 最近的价格暴涨发生在非常特定的时期,进一步表明它们可能是人为的。但该项目的创始人 Sasha Ivanov否认了这些指控,称 WAVES 最近的增长在很大程度上是有机的。他引用了类似的稳定币借贷模型,随后是其他 DeFi 平台。协议和Terra之间也进行了比较,因为它们都在类似的机制上运行,即 LUNA 可以被烧毁以铸造 TerraUSD。但 Terra 已积极降低其贷款利率以确保可持续性,最近对Terra的DeFi 平台Anchor Protocol 的投票证明了这一点。Terra 还拥有大量的比特币和稳定币储备来支持其稳定币,而相对较小的平台 WAVES 无法证明这一点。

#defi #terra #WAVEs #dapp #bitcoin 

Waves被指控将崩盘?创始人Sasha Ivanov否认庞氏骗局?

Terra Token: Simple CosmWasm Smart Contract on Terra

CosmWasm Starter Pack

This is a template to build smart contracts in Rust to run inside a Cosmos SDK module on all chains that enable it. To understand the framework better, please read the overview in the cosmwasm repo, and dig into the cosmwasm docs. This assumes you understand the theory and just want to get coding.

Creating a new repo from template

Assuming you have a recent version of rust and cargo installed (via rustup), then the following should get you a new repo to start a contract:

First, install cargo-generate. Unless you did that before, run this line now:

cargo install cargo-generate --features vendored-openssl

Now, use it to create your new contract. Go to the folder in which you want to place it and run:

Stable (0.8)

cargo generate --git https://github.com/CosmWasm/cosmwasm-template.git --name YOUR_NAME_HERE

You will now have a new folder called YOUR_NAME_HERE (I hope you changed that to something else) containing a simple working contract and build system that you can customize.

Create a Repo

After generating, you have a initialized local git repo, but no commits, and no remote. Go to a server (eg. github) and create a new upstream repo (called YOUR-GIT-URL below). Then run the following:

# this is needed to create a valid Cargo.lock file (see below)
cargo check
git checkout -b master # in case you generate from non-master
git add .
git commit -m 'Initial Commit'
git remote add origin YOUR-GIT-URL
git push -u origin master

CI Support

We have template configurations for both GitHub Actions and Circle CI in the generated project, so you can get up and running with CI right away.

One note is that the CI runs all cargo commands with --locked to ensure it uses the exact same versions as you have locally. This also means you must have an up-to-date Cargo.lock file, which is not auto-generated. The first time you set up the project (or after adding any dep), you should ensure the Cargo.lock file is updated, so the CI will test properly. This can be done simply by running cargo check or cargo unit-test.

Using your project

Once you have your custom repo, you should check out Developing to explain more on how to run tests and develop code. Or go through the online tutorial to get a better feel of how to develop.

Publishing contains useful information on how to publish your contract to the world, once you are ready to deploy it on a running blockchain. And Importing contains information about pulling in other contracts or crates that have been published.

Please replace this README file with information about your specific project. You can keep the Developing.md and Publishing.md files as useful referenced, but please set some proper description in the README.

Download Details:
Author: terra-money
Source Code: https://github.com/terra-money/my-terra-token
License: Apache-2.0 License

#rust  #blockchain  #terra 

Terra Token: Simple CosmWasm Smart Contract on Terra

CosmWasm Plus: Production Quality Contracts Under Open Source Licenses

CosmWasm Plus

This is a collection of specification and contracts designed for use on real networks. They are designed not just as examples, but to solve real-world use cases, and to provide a reusable basis to build many custom contracts.

If you don't know what CosmWasm is, please check out our homepage and our documentation to get more background. We are running a public testnet you can use to test out any contracts.

Warning None of these contracts have been audited and no liability is assumed for the use of this code. They are provided to turbo-start your projects.

Note All code in pre-1.0 packages is in "draft" form, meaning it may undergo minor changes and additions until 1.0. For example between 0.1 and 0.2 we adjusted the Expiration type to make the JSON representation cleaner (before: expires: {at_height: {height: 12345}} after expires: {at_height: 12345})

Specifications

The most reusable components are the various cwXYZ specifications under packages. Each one defines a standard interface for different domains, e.g. cw20 for fungible tokens, cw721 for non-fungible tokens, cw1 for "proxy contracts", etc. The interface comes with a human description in the READMEs, as well as Rust types that can be imported.

They contain no logic, but specify an interface. It shows what you need to implement to create a compatible contracts, as well as what interface we guarantee to any consumer of such contracts. This is the real bonus of specifications, we can create an escrow contract that can handle many different fungible tokens, as long as they all adhere to the cw20 specification.

If you have ideas for new specifications or want to make enhancements to existing spec, please raise an issue or create a pull request on this repo.

Contracts

We provide sample contracts that either implement or consume these specifications to both provide examples, and provide a basis for code you can extend for more custom contacts, without worrying about reinventing the wheel each time. For example cw20-base is a basic implementation of a cw20 compatible contract that can be imported in any custom contract you want to build on it.

CW1 Proxy Contracts:

  • cw1-whitelist a minimal implementation of cw1 mainly designed for reference.
  • cw1-subkeys a simple, but useful implementation, which lets us use a proxy contract to provide "allowances" for native tokens without modifying the bank module.

CW3 Multisig:

  • cw3-fixed-multisig a simple implementation of the cw3 spec. It is a multisig with a fixed set of addresses, created upon initialization. Each address may have the same weight (K of N), or some may have extra voting power. This works much like the native Cosmos SDK multisig, except that rather than aggregating the signatures off chain and submitting the final result, we aggregate the approvals on-chain.
  • cw3-flex-multisig builds on cw3-fixed-multisig, with a more powerful implementation of the cw3 spec. It's a multisig contract backed by a cw4 (group) contract, which independently maintains the voter set.

CW4 Group:

  • cw4-group a basic implementation of the cw4 spec. It handles elected membership, by admin or multisig. It fulfills all elements of the spec, including raw query lookups, and is designed to be used as a backing storage for cw3 compliant contracts.
  • cw4-stake a second implementation of the cw4 spec. It fulfills all elements of the spec, including raw query lookups, and is designed to be used as a backing storage for cw3 compliant contracts. It provides a similar API to [cw4-group], but rather than appointing members, their membership and weight are based on the number of staked tokens they have.

CW20 Fungible Tokens:

  • cw20-base a straightforward, but complete implementation of the cw20 spec along with all extensions. Can be deployed as-is, or imported by other contracts.
  • cw20-atomic-swap an implementation of atomic swaps for both native and cw20 tokens.
  • cw20-bonding a smart contract implementing arbitrary bonding curves, which can use native and cw20 tokens as reserve tokens.
  • cw20-staking provides staking derivatives, staking native tokens on your behalf and minting cw20 tokens that can be used to claim them. It uses cw20-base for all the cw20 logic and only implements the interactions with the staking module and accounting for prices.
  • cw20-escrow is a basic escrow contract (arbiter can release or refund tokens) that is compatible with all native and cw20 tokens. This is a good example to show how to interact with cw20 tokens.

CW721 Non-fungible Tokens:

  • cw721-base a base implementation of a cw721 NFT contract. It implements the CW721 spec and is designed to be deployed as is, or imported into other contracts to easily build cw721-compatible NFTs with custom logic.

Compiling

To compile all the contracts, run the following in the repo root:

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/workspace-optimizer:0.11.0

This will compile all packages in the contracts directory and output the stripped and optimized wasm code under the artifacts directory as output, along with a checksums.txt file.

If you hit any issues there and want to debug, you can try to run the following in each contract dir: RUSTFLAGS="-C link-arg=-s" cargo build --release --target=wasm32-unknown-unknown --locked

Quality Control

One of the basic metrics of assurance over code quality is how much is covered by unit tests. There are several tools available for Rust to do such analysis and we will describe one below. This should be used as a baseline metric to give some confidence in the code.

Beyond code coverage metrics, just having a robust PR review process with a few more trained eyes looking for bugs is very helpful in detecting paths the original coder was not aware of. This is more subjective, but looking at the relevant PRs and depth of discussion can give an idea how much review was present.

After that, fuzzing it (ideally with an intelligent fuzzer that understands the domain) can be valuable. And beyond that formal verification can provide even more assurance (but is very time consuming and expensive).

Code Coverage

I recommend the use of tarpaulin: cargo install cargo-tarpaulin

To get some nice interactive charts, you can go to the root directory and run:

cargo tarpaulin -o html and then xdg-open tarpaulin-report.html (or just open on MacOS).

Once you find a package that you want to improve, you can do the following to just analyze this package, which gives much faster turn-around:

cargo tarpaulin -o html --packages cw3-fixed-multisig

Note that it will produce a code coverage report for the entire project, but only the coverage in that package is the real value. If does give quick feedback for you if you unit test writing was successful.

SpecificationDownloadDocs
cw0cw0 on crates.ioDocs
cw1cw1 on crates.ioDocs
cw2cw2 on crates.ioDocs
cw3cw3 on crates.ioDocs
cw20cw20 on crates.ioDocs
cw721cw721 on crates.ioDocs
ContractsDownloadDocs
cw1-subkeyscw1-subkeys on crates.ioDocs
cw1-whitelistcw1-whitelist on crates.ioDocs
cw3-fixed-multisigcw3-fixed-multisig on crates.ioDocs
cw20-atomic-swapcw20-atomic-swap on crates.ioDocs
cw20-basecw20-base on crates.ioDocs
cw20-escrowcw20-escrow on crates.ioDocs
cw20-stakingcw20-staking on crates.ioDocs
cw721-basecw721-base on crates.ioDocs

Download Details:
Author: /terra-money
Source Code: https://github.com/terra-money/cosmwasm-plus
License: View license

#rust  #blockchain  #terra #cosmwasm 

CosmWasm Plus: Production Quality Contracts Under Open Source Licenses

Terra Cosmwasm: Terra Bindings for CosmWasm

Terra Bindings for CosmWasm

​ This crate provides Terra-specific bindings to enable your CosmWasm smart contracts to interact with the Terra blockchain by exposing messages and queriers that can be emitted and used from within your contract. ​

Installation

​ Add the following to your smart contract's Cargo.toml: ​

[dependencies]
terra-cosmwasm = { version = "1.2" }

Contents

​ Currently, the Terra bindings include: ​

  • Query support for:
    • Market
      • swap rate between 2 currencies at market price
    • Treasury
      • current tax cap for a denomination
      • current tax rate
    • Oracle
      • exchange rates for the given base_denom / quote_denoms ​
  • Messages
    • MsgSwap
    • MsgSwapSend

Usage

Querying

​ In order to use the query functions enabled by the bindings, create a TerraQuerier instance within your contract logic -- in either init(), handle(), or query() entrypoints. You can access all the enabled queries through this object. ​​

// src/contract.rs
use cosmwasm_std::Coin;
use terra_cosmwasm::{ TerraQuerier, SwapResponse, TaxRateResponse, TaxCapResponse, ExchangeRatesResponse };
​
...
​
// handler
pub fn try_something<S: Storage, A: Api, Q: Querier>(
    deps: &mut Extern<S, A, Q>,
    env: Env,
    offer: &Coin
) -> StdResult<HandleResponse> {
    let querier = TerraQuerier::new(&deps.querier);
    let swap_rate: SwapResponse = querier.query_swap(offer.clone(), "uusd")?;
    let tax_cap: TaxCapResponse = querier.query_tax_cap("usdr")?;
    let tax_rate: TaxRateResponse = querier.query_tax_rate()?;
    let exchange_rates: ExchangeRatesResponse = querier.query_exchange_rates("uusd", vec!["uluna", "ukrw"])?;
    ...
}

Creating Messages​

NOTE: The Terra bindings do not cover messages that have already been implemented by the CosmWasm team, such as staking-related messages and fundamental ones like MsgSend. ​ You may want your contract to perform messages such as MsgSwap and MsgSwapSend operations at the end of its execution. To do this, create a message using the predefined functions: ​

  • create_swap_msg
  • create_swap_send_msg ​ And add it to the vector of messages in your HandleResponse before you return Ok. ​
use cosmwasm_std::CosmosMsg;
use terra_cosmwasm::{create_swap_msg, TerraMsgWrapper};
​
...
​
pub fn try_something<S: Storage, A: Api, Q: Querier>(
  deps: &mut Extern<S, A, Q>,
  env: Env,
  offer: &Coin
) -> StdResult<HandleResponse<TerraMsgWrapper>> {
  ...
​
  let msg: CosmosMsg<TerraMsgWrapper> = create_swap_msg(contract_addr, offer_coin, ask_denom);
  let res = HandleResponse {
      messages: vec![msg],
      log: vec![],
      data: None
  };
  Ok(res)
}

Download Details:
Author: terra-money
Source Code: https://github.com/terra-money/terra-cosmwasm
License:

#rust  #blockchain  #terra #CosmWasm #smartcontract 

Terra Cosmwasm: Terra Bindings for CosmWasm

Cosmwasm Examples: A Collection Of Contracts Built with The Cosmwasm

Cosmwasm Examples

This repo is a collection of contracts built with the cosmwasm framework. Anyone building on cosmwasm is encouraged to submit their contracts as a sub-project via a PR.

The organization is relatively simple. The top-level directory is just a placeholder and has no real code. And we use workspaces to add multiple contracts below. This allows us to compile all contracts with one command.

Usage

Sample contracts are available under the contracts/ directory. You can view the source code under each contract’s src subdirectory. Take a look here:

Development

Starting a contract

If you want to add a contract, first fork this repo and create a branch for your PR. I suggest setting it up via cosmwasm-template:

cargo generate --git https://github.com/confio/cosmwasm-template.git --name FOO

Then update the README.md to reflect your actual contract (just read the README.md in the autogenerated template - it explains a lot).

Preparing for merge

Before you merge the code, make sure it builds and passes all tests, both in the package, and when calling it from the root packages cargo wasm && cargo test. This should show your package is covered by the CI.

There is also quite some useful information in Development.md and Publishing.md in the newly generated contract.

You should also prepare a compiled contract.wasm before each merge to master. This is not enforced by the CI (a full build each commit), but should be tested on merge. See cosmwasm-opt for an explanation of how to make a deterministic build.

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/rust-optimizer:0.11.3

Download Details:
Author: terra-money
Source Code: https://github.com/terra-money/cosmwasm-contracts
License: Apache-2.0 License

#rust  #blockchain  #terra #contract 

Cosmwasm Examples: A Collection Of Contracts Built with The Cosmwasm

Cosmwasm: Library for Building Cosmos Compatible Wasm Smart Contracts

CosmWasm

WebAssembly Smart Contracts for the Cosmos SDK.

Overview

To get that contract to interact with a system needs many moving parts. To get oriented, here is a list of the various components of the CosmWasm ecosystem:

Standard library:

This code is compiled into Wasm bytecode as part of the smart contract.

  • cosmwasm-std - A crate in this workspace. Provides the bindings and all imports needed to build a smart contract.
  • cosmwasm-storage - A crate in this workspace. This optional addition to cosmwasm-std includes convenience helpers for interacting with storage.
  • cw-storage-plus - A crate in cosmwasm-plus, which fills the same role as cosmwasm-storage, but with much more powerful types supporting composite primary keys, secondary indexes, automatic snapshotting, and more. This is newer and a bit less stable than cosmwasm-storage but used in most modern contracts.

Building contracts:

  • cosmwasm-template - A starter-pack to get you quickly building your custom contract compatible with the cosmwasm system.
  • cosmwasm-plus - Some sample contracts for use and inspiration. These provide usable primitives and interfaces for many use cases, such as fungible tokens, NFTs, multisigs, governance votes, staking derivatives, and more. Look in packages for docs on the various standard interfaces, and contracts for the implementations. Please submit your contract or interface via PR.
  • rust-optimizer - A docker image and scripts to take your Rust code and produce the smallest possible Wasm output, deterministically. This is designed both for preparing contracts for deployment as well as validating that a given deployed contract is based on some given source code, allowing a similar contract verification algorithm as Etherscan.
  • serde-json-wasm - A custom json library, forked from serde-json-core. This provides an interface similar to serde-json, but without any floating-point instructions (non-deterministic) and producing builds around 40% of the code size.

Executing contracts:

  • cosmwasm-vm - A crate in this workspace. Uses the wasmer engine to execute a given smart contract. Also contains code for gas metering, storing, and caching wasm artifacts.
  • wasmvm - High-level go bindings to all the power inside cosmwasm-vm. Easily allows you to upload, instantiate and execute contracts, making use of all the optimizations and caching available inside cosmwasm-vm.
  • wasmd - A basic Cosmos SDK app to host WebAssembly smart contracts. It can be run as is, or you can import the x/wasm module from it and use it in your blockchain. It is designed to be imported and customized for other blockchains, rather than forked.

Creating a Smart Contract

You can see some examples of contracts under the contracts directory, which you can look at. They are simple and self-contained, primarily meant for testing purposes, but that also makes them easier to understand.

You can also look at cosmwasm-plus for examples and inspiration on more production-like contracts and also how we call one contract from another. If you are working on DeFi or Tokens, please look at the cw20, cw721 and/or cw1155 packages that define standard interfaces as analogues to some popular ERC designs. (cw20 is also inspired by erc777).

If you want to get started building you own contract, the simplest way is to go to the cosmwasm-template repository and follow the instructions. This will give you a simple contract along with tests, and a properly configured build environment. From there you can edit the code to add your desired logic and publish it as an independent repo.

We also recommend you review our documentation site which contains a few tutorials to guide you in building your first contracts. We also do public workshops on various topics about once a month. You can find past recordings under the "Videos" section, or join our Discord server to ask for help.

Minimum Supported Rust Version (MSRV)

See Minimum Supported Rust Version (MSRV).

API entry points

WebAssembly contracts are basically black boxes. The have no default entry points, and no access to the outside world by default. To make them useful, we need to add a few elements.

If you haven't worked with WebAssembly before, please read an overview on how to create imports and exports in general.

Exports

The required exports provided by the cosmwasm smart contract are:

// signal for 1.0 compatibility
extern "C" fn interface_version_8() -> () {}

// copy memory to/from host, so we can pass in/out Vec<u8>
extern "C" fn allocate(size: usize) -> u32;
extern "C" fn deallocate(pointer: u32);

// main contract entry points
extern "C" fn instantiate(env_ptr: u32, info_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn execute(env_ptr: u32, info_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn query(env_ptr: u32, msg_ptr: u32) -> u32;

Contracts may also implement one or more of the following to extend their functionality:

// in-place contract migrations
extern "C" fn migrate(env_ptr: u32, info_ptr: u32, msg_ptr: u32) -> u32;

// support submessage callbacks
extern "C" fn reply(env_ptr: u32, msg_ptr: u32) -> u32;

// expose privileged entry points to Cosmos SDK modules, not external accounts
extern "C" fn sudo(env_ptr: u32, msg_ptr: u32) -> u32;

// and to write an IBC application as a contract, implement these:
extern "C" fn ibc_channel_open(env_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn ibc_channel_connect(env_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn ibc_channel_close(env_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn ibc_packet_receive(env_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn ibc_packet_ack(env_ptr: u32, msg_ptr: u32) -> u32;
extern "C" fn ibc_packet_timeout(env_ptr: u32, msg_ptr: u32) -> u32;

allocate/deallocate allow the host to manage data within the Wasm VM. If you're using Rust, you can implement them by simply re-exporting them from cosmwasm::exports. instantiate, execute and query must be defined by your contract.

Imports

The imports provided to give the contract access to the environment are:

// This interface will compile into required Wasm imports.
// A complete documentation those functions is available in the VM that provides them:
// https://github.com/CosmWasm/cosmwasm/blob/v1.0.0-beta/packages/vm/src/instance.rs#L89-L206
extern "C" {
    fn db_read(key: u32) -> u32;
    fn db_write(key: u32, value: u32);
    fn db_remove(key: u32);

    // scan creates an iterator, which can be read by consecutive next() calls
    #[cfg(feature = "iterator")]
    fn db_scan(start_ptr: u32, end_ptr: u32, order: i32) -> u32;
    #[cfg(feature = "iterator")]
    fn db_next(iterator_id: u32) -> u32;

    fn addr_validate(source_ptr: u32) -> u32;
    fn addr_canonicalize(source_ptr: u32, destination_ptr: u32) -> u32;
    fn addr_humanize(source_ptr: u32, destination_ptr: u32) -> u32;

    /// Verifies message hashes against a signature with a public key, using the
    /// secp256k1 ECDSA parametrization.
    /// Returns 0 on verification success, 1 on verification failure, and values
    /// greater than 1 in case of error.
    fn secp256k1_verify(message_hash_ptr: u32, signature_ptr: u32, public_key_ptr: u32) -> u32;

    fn secp256k1_recover_pubkey(
        message_hash_ptr: u32,
        signature_ptr: u32,
        recovery_param: u32,
    ) -> u64;

    /// Verifies a message against a signature with a public key, using the
    /// ed25519 EdDSA scheme.
    /// Returns 0 on verification success, 1 on verification failure, and values
    /// greater than 1 in case of error.
    fn ed25519_verify(message_ptr: u32, signature_ptr: u32, public_key_ptr: u32) -> u32;

    /// Verifies a batch of messages against a batch of signatures and public keys, using the
    /// ed25519 EdDSA scheme.
    /// Returns 0 on verification success, 1 on verification failure, and values
    /// greater than 1 in case of error.
    fn ed25519_batch_verify(messages_ptr: u32, signatures_ptr: u32, public_keys_ptr: u32) -> u32;

    /// Writes a debug message (UFT-8 encoded) to the host for debugging purposes.
    /// The host is free to log or process this in any way it considers appropriate.
    /// In production environments it is expected that those messages are discarded.
    fn debug(source_ptr: u32);

    /// Executes a query on the chain (import). Not to be confused with the
    /// query export, which queries the state of the contract.
    fn query_chain(request: u32) -> u32;
}

(from imports.rs)

You could actually implement a WebAssembly module in any language, and as long as you implement these functions, it will be interoperable, given the JSON data passed around is the proper format.

Note that these u32 pointers refer to Region instances, containing the offset and length of some Wasm memory, to allow for safe access between the caller and the contract:

/// Describes some data allocated in Wasm's linear memory.
/// A pointer to an instance of this can be returned over FFI boundaries.
///
/// This struct is crate internal since the cosmwasm-vm defines the same type independently.
#[repr(C)]
pub struct Region {
    /// The beginning of the region expressed as bytes from the beginning of the linear memory
    pub offset: u32,
    /// The number of bytes available in this region
    pub capacity: u32,
    /// The number of bytes used in this region
    pub length: u32,
}

(from memory.rs)

Implementing the Smart Contract

If you followed the instructions above, you should have a runable smart contract. You may notice that all of the Wasm exports are taken care of by lib.rs, which should shouldn't need to modify. What you need to do is simply look in contract.rs and implement instantiate and execute functions, defining your custom InstantiateMsg and ExecuteMsg structs for parsing your custom message types (as json):

#[entry_point]
pub fn instantiate(
  deps: DepsMut,
  env: Env,
  info: MessageInfo,
  msg: InstantiateMsg,
) -> Result<Response, ContractError> {}

#[entry_point]
pub fn execute(
  deps: DepsMut,
  env: Env,
  info: MessageInfo,
  msg: ExecuteMsg,
) -> Result<Response, ContractError> {}

#[entry_point]
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> Result<Binary, ContractError> {}

#[entry_point]
pub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {}

The low-level db_read and db_write imports are nicely wrapped for you by a Storage implementation (which can be swapped out between real Wasm code and test code). This gives you a simple way to read and write data to a custom sub-database that this contract can safely write as it wants. It's up to you to determine which data you want to store here:

/// Storage provides read and write access to a persistent storage.
/// If you only want to provide read access, provide `&Storage`
pub trait Storage {
    /// Returns None when key does not exist.
    /// Returns Some(Vec<u8>) when key exists.
    ///
    /// Note: Support for differentiating between a non-existent key and a key with empty value
    /// is not great yet and might not be possible in all backends. But we're trying to get there.
    fn get(&self, key: &[u8]) -> Option<Vec<u8>>;

    #[cfg(feature = "iterator")]
    /// Allows iteration over a set of key/value pairs, either forwards or backwards.
    ///
    /// The bound `start` is inclusive and `end` is exclusive.
    ///
    /// If `start` is lexicographically greater than or equal to `end`, an empty range is described, mo matter of the order.
    fn range<'a>(
        &'a self,
        start: Option<&[u8]>,
        end: Option<&[u8]>,
        order: Order,
    ) -> Box<dyn Iterator<Item = Record> + 'a>;

    fn set(&mut self, key: &[u8], value: &[u8]);

    /// Removes a database entry at `key`.
    ///
    /// The current interface does not allow to differentiate between a key that existed
    /// before and one that didn't exist. See https://github.com/CosmWasm/cosmwasm/issues/290
    fn remove(&mut self, key: &[u8]);
}

(from traits.rs)

Testing the Smart Contract (rust)

For quick unit tests and useful error messages, it is often helpful to compile the code using native build system and then test all code except for the extern "C" functions (which should just be small wrappers around the real logic).

If you have non-trivial logic in the contract, please write tests using rust's standard tooling. If you run cargo test, it will compile into native code using the debug profile, and you get the normal test environment you know and love. Notably, you can add plenty of requirements to [dev-dependencies] in Cargo.toml and they will be available for your testing joy. As long as they are only used in #[cfg(test)] blocks, they will never make it into the (release) Wasm builds and have no overhead on the production artifact.

Note that for tests, you can use the MockStorage implementation which gives a generic in-memory hashtable in order to quickly test your logic. You can see a simple example how to write a test in our sample contract.

Testing the Smart Contract (wasm)

You may also want to ensure the compiled contract interacts with the environment properly. To do so, you will want to create a canonical release build of the <contract>.wasm file and then write tests in with the same VM tooling we will use in production. This is a bit more complicated but we added some tools to help in cosmwasm-vm which can be added as a dev-dependency.

You will need to first compile the contract using cargo wasm, then load this file in the integration tests. Take a look at the sample tests to see how to do this... it is often quite easy to port a unit test to an integration test.

Production Builds

The above build process (cargo wasm) works well to produce wasm output for testing. However, it is quite large, around 1.5 MB likely, and not suitable for posting to the blockchain. Furthermore, it is very helpful if we have reproducible build step so others can prove the on-chain wasm code was generated from the published rust code.

For that, we have a separate repo, rust-optimizer that provides a docker image for building. For more info, look at rust-optimizer README, but the quickstart guide is:

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/rust-optimizer:0.12.3

It will output a highly size-optimized build as contract.wasm in $CODE. With our example contract, the size went down to 126kB (from 1.6MB from cargo wasm). If we didn't use serde-json, this would be much smaller still...

Benchmarking

You may want to compare how long the contract takes to run inside the Wasm VM compared to in native rust code, especially for computationally intensive code, like hashing or signature verification.

TODO add instructions

Developing

The ultimate auto-updating guide to building this project is the CI configuration in .circleci/config.yml.

For manually building this repo locally during development, here are a few commands. They assume you use a stable Rust version by default and have a nightly toolchain installed as well.

Workspace

# Compile and lint
./devtools/check_workspace.sh

# Run tests
./devtools/test_workspace.sh

Contracts

StepDescriptionCommand
1fast checks, rebuilds lock files./devtools/check_contracts_fast.sh
2medium fast checks./devtools/check_contracts_medium.sh
3slower checks./devtools/check_contracts_full.sh

Packages

The following packages are maintained here:

CrateUsageDownloadDocsCoverage
cosmwasm-cryptoInternal onlycosmwasm-crypto on crates.ioDocs[![Coverage][cov-badge-crypto]][cov-link-crypto]
cosmwasm-deriveInternal onlycosmwasm-derive on crates.ioDocs[![Coverage][cov-badge-derive]][cov-link-derive]
cosmwasm-schemaContract developmentcosmwasm-schema on crates.ioDocs[![Coverage][cov-badge-schema]][cov-link-schema]
cosmwasm-stdContract developmentcosmwasm-std on crates.ioDocs[![Coverage][cov-badge-std]][cov-link-std]
cosmwasm-storageContract developmentcosmwasm-storage on crates.ioDocs[![Coverage][cov-badge-storage]][cov-link-storage]
cosmwasm-vmHost environmentscosmwasm-vm on crates.ioDocs([#1151])

Download Details:
Author: terra-money
Source Code: https://github.com/terra-money/cosmwasm
License: Apache-2.0 License

#rust  #blockchain  #terra #smartcontract #webassembly 

Cosmwasm: Library for Building Cosmos Compatible Wasm Smart Contracts

Certus One's Reference Node Implementation for The Wormhole

Wormhole v2

This repository contains Certus One's reference node implementation for the Wormhole project.

See DEVELOP.md for instructions on how to set up a local devnet, and CONTRIBUTING.md for instructions on how to contribute to this project.

See docs/operations.md for node operator instructions.

Wormhole v2 is in active development - see "main" branch for the v1 mainnet version

Audit / Feature Status

This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Or plainly spoken - this is a very complex piece of software which targets a bleeding-edge, experimental smart contract runtime. Mistakes happen, and no matter how hard you try and whether you pay someone to audit it, it may eat your tokens, set your printer on fire or startle your cat. Cryptocurrencies are a high-risk investment, no matter how fancy.

Download Details:
Author: terra-money
Source Code: https://github.com/terra-money/wormhole
License: View license

#rust  #blockchain  #terra #typescript #protocol 

Certus One's Reference Node Implementation for The Wormhole

TeFi Oracle: Oracle SmartContracts for TeFi Projects

TeFi Oracle

This repository contains the source code for a set of oracle smart contracts running on Terra blockchain.

Contracts

ContractReferenceDescription
hubdocCentral price source for all assets, redirects requests to proxies based on priority and availability
proxy-templatedocTemplate of a contract that implements the proxy standard
proxy-banddocProxy contract for Band Protocol price sources
proxy-chainlinkdocProxy contract for Chainlink price sources
proxy-feeddocCustom proxy contract that allows external sources to feed prices

Development

Environment Setup

  • Rust v1.44.1+
  • wasm32-unknown-unknown target
  • Docker
  1. Install rustup via https://rustup.rs/
  2. Run the following:
rustup default stable
rustup target add wasm32-unknown-unknown

3.   Make sure Docker is installed

Unit / Integration Tests

Each contract contains Rust unit and integration tests embedded within the contract source directories. You can run:

cargo unit-test
cargo integration-test

Compiling

After making sure tests pass, you can compile each contract with the following:

RUSTFLAGS='-C link-arg=-s' cargo wasm
cp ../../target/wasm32-unknown-unknown/release/cw1_subkeys.wasm .
ls -l cw1_subkeys.wasm
sha256sum cw1_subkeys.wasm

Production

For production builds, run the following:

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/rust-optimizer:0.11.5

or

sh build_release.sh

This performs several optimizations which can significantly reduce the final size of the contract binaries, which will be available inside the artifacts/ directory.

Formatting

Make sure you run rustfmt before creating a PR to the repo. You need to install the nightly version of rustfmt.

rustup toolchain install nightly

To run rustfmt,

cargo fmt

Linting

You should run clippy also. This is a lint tool for rust. It suggests more efficient/readable code. You can see the clippy document for more information. You need to install nightly version of clippy.

Install

rustup toolchain install nightly

Run

cargo clippy --all --all-targets -- -D warnings

Testing

Developers are strongly encouraged to write unit tests for new code, and to submit new unit tests for old code. Unit tests can be compiled and run with: cargo test --all. For more details, please reference Unit Tests.

Download Details:
Author: terra-money
Source Code: https://github.com/terra-money/tefi-oracle-contracts
License:

#rust  #blockchain  #terra #smartcontract #oracle 

TeFi Oracle: Oracle SmartContracts for TeFi Projects

A Multisend Smart Contract for The Terra Blockchain using CosmWasm

CosmWasm Multisend Contract

This is a multisend smart contracts in Rust built to run on Cosmos SDK module on all chains that enable it. The project was built and tested for the Terra network.

What it does

This project covers all that is required to build, deploy and interact with the smart contract on the Terra blockchain. The main parts of the project are:

  • The contract (this page)
  • The deployment scripts in scripts
  • A basic CLI client application to send and receive Terra/Luna as well as interact with the deployed contract: multisender-client

Each part has its own README and instructions

Multisend Contract

The contract is written in Rust and is compiled to wasm. The contract receives a list of addresses and amounts, and distributes the passed coins to these addresses. The amount sent to the contract must be enough to cover the outgoing payments.

The contract also includes a possible fee, set on contract initialization. The fee is paid to the contract owner and must be added to the total payment received by the contract when creating a transaction. The script in multisender-client queries the contract and adds the required fee to the transaction.

Prerequisites

Building the contract requires an up-to-date Rust version with wasm support.

rustup default stable
rustup target add wasm32-unknown-unknown

For further details, consult the official Terra documentation for setting up the environment.

As a live test environment, it is recommended to use LocalTerra. Follow the installation process of LocalTerra in the link

Building the contract

Clone the contract to a new environment.

git clone https://github.com/ZenGo-X/terra-multisend.git

Make sure the project compiles by running

cargo wasm

This will build an unoptimized version of the contract, just to make sure the compilation works. To build an optimized version that can be uploaded to the blockchain, run

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/rust-optimizer:0.10.3

More instructions on building and developing the contract in Developing

Once the contract is compiled, go to scripts to deploy the contract using Terra.js

Contract use cases and limitations

The Terra blockchain supports sending multiple payments simultaneously via a MsgMultiSend. Still, the contract could be useful for several use cases:

  • Integration with other smart contracts
  • Sending ERC20/CW20 tokens (in future versions)
  • Collecting payment for the provided service

The contract can be also easily extended to perform additional tasks, such as swapping tokens to the required coin etc.

Contract Demo

In the demo, the contract sends a batch of transactors to the addresses specified in the CSV. The The address of sending address gets funds removed, and added to the specified addresses. This is easy to practice in LocalTerra, as it several addresses with funds for testing. Do not use these addresses in production

demon

Misc

Publishing contains useful information on how to publish your contract, once you are ready to deploy it on a running blockchain. Importing contains information about pulling in other contracts or crates that have been published.

Download Details:
Author: 
Source Code: 
License:

#rust  #blockchain #terra 

A Multisend Smart Contract for The Terra Blockchain using CosmWasm
黎 飞

黎 飞

1641469260

Terra(LUNA)虚拟币价格分析及未来发展,值得关注的Columbus 5(哥伦布五号)升级

去中心化金融并非完全去中心化。除了许多 DeFi 协议由单个公司或一小部分个人运营这一事实之外,占其锁定总价值的大部分的稳定币都是中央控制的。

不仅如此加密货币的大部分交易量都来自稳定币交易对。这是一个问题,因为如果监管机构要关闭这些稳定币发行商,它就会淘汰 DeFi,可能会导致加密货币市场的发展停滞。

Terra 近年来表现不错,其 UST 稳定币作为 USDT和USDC以及BUSD 的去中心化替代品越来越受欢迎。本期视频我将向你简要介绍 Terra 的一些最新消息和Terra LUNA未来可能的发展方向。在我之前的视频中已经介绍过Terra LUNA,如果你还不知道它,可以通过我的频道首页观看我之前的视频,本期就不再重复介绍了。

要铸造 UST 或任何其他 Terra 稳定币,必须燃烧等量的 LUNA。因此举一个简单的例子,如果一个 LUNA 值 10 美元,燃烧一个 LUNA 将铸造 10 UST。

因为 UST 也可以被烧毁以铸造等值美元的 LUNA,这为 UST 维持其价值挂钩创造了必要的经济激励。如果 UST 的交易价格为 1 美元,则 LUNA 持有者可以燃烧他们的硬币来铸造 UST 并获得利润。

或者如果 UST 的交易价格为 50 美分,UST 持有者可以燃烧他们的代币来铸造 LUNA 并获得 2 倍的利润。这减少了流通中的 UST 数量,从而恢复了与1美元的价值挂钩。因此每次 LUNA 被烧毁以铸造 UST 时,都会收取少量费用并将其存入社区金库,以资助新的 Terra 项目和协议。

Terra 的权益证明区块链使这个巧妙的系统成为可能,该区块链是使用Cosmos SDK构建的。Terra 的区块链每秒可以处理几百笔交易,并且有 130 个验证器。这些兼作预言机用于检查 LUNA和Terra 的各种稳定币之间的汇率。

尽管对于验证者来说,Terra 没有最低股份。LUNA 的质押量必须足够大,以便按质押排在前 130 名验证者中。任何委派的 LUNA 均计入此数量。目前验证人和委托人的质押奖励每年不到 6%,任何质押的 LUNA 都需要21天才能退出。

请注意Terra 确实削减了任何行为不端的验证者的 LUNA 权益。LUNA 的初始供应量为 10 亿,将30%分配给 Terraform Labs 及其员工,20%分配给 Terra Alliance,26%分配给投资者,4%分配给交易所流动性,20%分配给稳定储备,在一定程度上防止可能出现的市场波动。

从技术上讲Terra 的动态最大供应量为 10 亿。基本上如果LUNA少于10亿,新的LUNA会逐渐铸造,如果LUNA超过10亿,过剩的供应会逐渐燃烧。

在过去的几个月里Terraform Labs 的投资部门向希望利用 Terra 的 UST 稳定币的加密项目投入了数百万美元。Terra 的稳定储蓄协议称为Anchor(也有人叫锚定协议),Terra 的合成股票交易平台称为Mirror。最近Terraform 资本投资于Nexus Protocol,希望即使在市场崩盘时,也能从存入 Anchor Protocol 的资金中保持稳定的收益。

关于Terra 的哥伦布 5 升级

就 Terra 未来的计划而言,即将有一个巨大的更新。Columbus 5将成为 Terra 主网发布以来最重大的升级,它将为 Terra 区块链引入三项新功能。

首先是烧掉所有的senidge费用。Senioridge 只是用来描述燃烧 LUNA 铸造UST的小额费用的术语。正如我之前提到的一样,这笔费用属于社区金库。问题是 Terra 的社区金库已经持有超过 9300 万个 LUNA,价值高达 28 亿美元。如果我没记错的话这将使 Terra 的社区金库成为所有加密货币项目或协议中最大的。这将给 LUNA 增加通缩压力,这可能会增加代币的价值,进而增加社区金库的价值。我认为他们称之为双赢。

Columbus 5将为Terra 带来的第二个功能是与 Cosmos 的区块链间通信协议或 IBC 的互操作性。IBC 基本上可以将每个加密货币区块链连接在一起。加密货币区块链之间已经有几十个桥梁,那IBC又有什么特别之处?

假设你已将比特币包装在以太坊上,并且你想将包装好的比特币转移到币安智能链。你必须通过将比特币发送回比特币区块链来解开比特币,然后再次将其重新包装以在币安智能链上使用,但这样做并不是很高效。

在这种情况下IBC 通过将所有区块链桥接到一个中心来工作,即 Cosmos 区块链本身。使用 IBC你可以将以太坊上打包的比特币直接转移到 Binance 智能链,而无需返回比特币。这可以为你节省大量时间和金钱。Terra 在这个等式中的重要性当然是 UST,它将成为使用 Cosmos 的下一代 DEX在IBC 上交易跨链资产的去中心化稳定币。Columbus 5 将为 Terra 带来的第三个功能是去中心化保险协议 Ozone。Columbus 5 还将通过虫洞桥正式启用对 Solana 区块链的支持,所有这些都将在9月底,很有可能在9月29日发布。虽然很多人这些利好消息已经被最近的不断的跌幅所质疑,但这些东西确实能提起一些信心。

关于LUNA价格分析

所有这些公告和发展都对 LUNA 产生了可预测的影响,LUNA 之前反弹超过了上次的历史新高。这种影响从根本上归结为对 LUNA 铸造 UST 的需求增加,其市值在过去几个月中也呈指数增长。

对 UST 的大部分需求来自 Terra的DeFi 协议,如果我没记错的话,这可能会使 Terra 成为锁定总价值的第三大加密货币区块链。第一个是以太坊,第二个是币安智能链。

在这一点上 Terra 的团队和社区一直在努力推动 UST 在尽可能多的加密货币区块链上运行。目前可以在以太坊和币安智能链上找到 UST,而 Solana 似乎是下一个。考虑到 Solana 至少目前是 DeFi TVL 的下一个最大的加密货币,这是合乎逻辑的。

我们已经知道UST于8月初在Coinbase上市的消息,至少可以说这是一个有点令人惊讶的举动。无论如何Coinbase 的 UST 上市也可以作为推动 Terra价格上涨的一个因素。尽管我认为 LUNA 的价格可能会攀升到 100 美元以上。这是因为 LUNA 的市值只有 140 亿美元,还有很大上升空间。唯一担心的是可能会有 LUNA 鲸鱼在背后出售。毕竟LUNA的大部分供应都流向了Terraform Labs和Terra Alliance以及早期投资者。

#luna #terra 

Terra(LUNA)虚拟币价格分析及未来发展,值得关注的Columbus 5(哥伦布五号)升级
黎 飞

黎 飞

1641414480

什么是Harmony(One)加密货币?

 近期有小伙伴评论希望了解Harmony(One)虚拟币,本期我们将讨论有关 Harmony One 硬币的所有信息。与许多其他加密项目一样,Harmony 正试图解决区块链可扩展性问题,让我们深入研究协议、背后的团队,当然还有我对它未来的想法。

自今年年初以来,智能合约加密货币的用户和去中心化应用程序出现了惊人的增长和总价值锁定(TVL)。他们中的大多数人将其归咎于以太坊高得不可思议的 gas 费用,这导致数十万用户涌入其他智能合约加密货币区块链。大多数替代加密货币没有利用实力取代以太坊,而是选择作为以太坊庞大生态系统的补充。其中一种加密货币是Harmony,它的合作方式在短短几个月内导致用户采用和开发呈指数级增长,这使 Harmony 成为迄今为止最成功的以太坊替代品之一。

Harmony 是一个高吞吐量、低延迟和低费用的平台,Harmony的创建者称它为未来的去中心化经济提供动力的平台。Harmony 项目本身专注于具有分散随机性的分片和安全抵押,同时它还实现了最佳跨分片路由和快速块传播。

与其竞争对手相比,Harmony 仍处于起步阶段,其市值为 20 亿美元排名第61位。Harmony ONE 的最大供应量为 131 亿枚,其中目前流通供应量为 100 亿枚。这些可以通过顶级交易所购买和交易,例如 Binance、Huobi Global和KuCoin。

Harmony 团队由 30 多名成员组成,该团队的 CEO 和领导者是 Stephen Tse。Stephen 是一位狂热的编码员,他一生都在研究和研究编译器和安全协议。他毕业于宾夕法尼亚大学,获得安全协议和编译器验证博士学位。之后他先后成为微软研究院研究员、谷歌高级基础架构工程师、苹果搜索排名首席工程师,之后成为 Spotsetter 创始人,后者后来被苹果收购。

一些值得注意的例子是 Harmony 和travala合作将 ONE 代币作为一种支付方式集成到旅游平台上。Harmony 和 UTU Protocol 之间还有合作伙伴关系,该合作伙伴关系推出了基于人工智能的预言机,以维护用户的信誉。另一个突破性的例子是 Harmony 和区块链教育网络 (BEN) 之间的合作伙伴关系,这两个团体合作开发新一代区块链开发人员的知识。

这主要是因为 Harmony 使用分片,这涉及将单个区块链分成称为分片的多个部分。Harmony 目前有四个分片,每个分片每秒可以处理 500 笔交易,总计 2000 tps。随着更多分片的添加Harmony 每秒的总交易量将增加。

Harmony 分片内的交易与分片之间在不到两秒内完成交易的速度一样快。这种快速的跨链通信是其他智能合约区块链目前正在努力解决的问题,即Polkadot 和 Kusama及其平行链。为了保护其四个分片 Harmony 使用了一种称为有效股权证明 (PoS) 或 EPoS 的股权证明(PoS) 共识机制。

这涉及将验证者随机分配给四个分片之一,如果他们的赌注太大则减少他们的赌注奖励。这是为了确保没有单个验证器增长到足以破坏分片。

Harmony 还使用 slashing 来控制验证器。Harmony 不会像大多数其他权益证明 (PoS) 加密货币那样削减验证器的停机时间,而且 Harmony 的抵押门槛非常低,10000个 ONE 是验证器的最低股份,1000个 ONE是委托人的最低股份,目前年回报率为10%。

虽然 ONE 是通货膨胀的,但这个通货膨胀率固定在每年 4.41 亿 ONE,相当于每年3%左右。这是比大多数其他通胀加密货币低得多的通胀率,不仅如此在 Harmony 区块链上发生足够多的交易,ONE 的通胀也可以完全消除。

既然说 ONE 永远不会出现通货紧缩,这是因为费用燃烧只是为了抵消新发行的 ONE,而不会在铸造后抵消现有供应中的ONE代币,所有用于支付费用的 ONE 代币都没有被烧毁。这是一种聪明的方法,可以通过通货膨胀在低交易量期间和通过费用奖励在高交易量期间确保稳健的抵押奖励。ONE 代币经济学唯一真正的缺点是 ONE 的供应是如何分配的并不完全清楚。

那么这在现实生活中意味着什么呢?Harmony 说他们帮助企业建立可替代代币使用的市场,例如忠诚度积分或能源信用以及不可替代的资产,例如游戏中的数字资产。它也有可能用于信用评级、广告交易和其他数据共享。

在 2019 年年中推出主网后,Harmony 取得了出色的增长,到去年年中已有超过 1000 个节点帮助分散网络。Harmony One 为 Harmony 平台提供动力,允许用户参与生态系统并作为各种行为的支付机制。Harmony ONE 代币在 Harmony 协议中设计为具有 3 个功能。

  • 首先代币被用作 EPoS 共识模型的质押,允许质押持有者获得奖励和交易费用。
     
  • 其次代币将支付交易和存储费用。
     
  • 最后 Harmony One 代币可用于协议本身的治理,允许代币持有者对链治理问题进行投票。


2020 年初 Harmony 开始将 ONE 代币从以太坊和币安链迁移到自己的区块链上。他们需要这样做才能实现质押和链上治理的计划。如果用户希望参与 Staking、治理或任何其他网络活动,则需要将他们的 ERC-20(以太坊)和 BEP-2(Binance)代币换成原生 ONE 代币。

这种“交换”过程是在任何参与 Harmony 桥梁的交易所自动完成的,包括 BitMax、Binance、KuCoin和Gateio。为了进行交换用户只需要在参与的交易所存入任何 ERC-20 或 BEP-2 ONE 代币,一旦提取原生 ONE 代币将被交付。

在今年4月Harmony 宣布已与流行的SushiSwap DEX合作,后者在 Harmony区块链上本地推出。在今年6月与 SushiSwap合作,宣布将向 Harmony 部署额外的 DEX 功能,并为早期采用者提供400 万美元的流动性挖矿奖励。最近,Harmony 与Terra (LUNA)建立了紧密的全栈合作伙伴关系。

这将使在 Harmony 区块链上使用 Terra 的 UST 稳定币成为可能,我们甚至会看到 Terra 流行的 Anchor 储蓄协议在 Harmony 上本地部署。最重要的是,Terra 的投资部门将为利用 UST 稳定币建立在 Harmony 上的阻尼器提供赠款和安全审计。

#Harmony #terra #cryto 

什么是Harmony(One)加密货币?
顾 静

顾 静

1641402000

公链赛道爆火的Terra,它的优势和面临的问题?

2021年年末Terra成为最后一匹从公链赛道杀出的黑马,其通证LUNA在12月24日首次突破100美元,较年初的最高涨幅已接近30倍。数据显示Terra稳定币UST市值已突破90亿美元,超过DAI成为市值排名第四的。而在更细分的算法稳定币赛道UST是妥妥的第一了。此外Terra是2021年总锁仓量TVL增长最快的区块链,其总锁仓量约为193亿美元年增长率达到35700%。目前Terra公链的总锁仓量位列行业第二,仅次于以太坊的1540亿美元,并在年末先后超越了Solana和Avalanche以及BSC。

众所周知信息科技产业相对发达的韩国,近年来同样孕育出了可观的互联网经济业态,但限于人口和市场规模,在中美主导的这轮商业革命中并无存在感。此外财阀把控经济命脉和普通阶层难以逆袭的情势下,韩国年轻人开始将加密资产作为翻身的寄托,炒币热度在全球各国中鲜有胜者。这两大背景共同催生了Terra这一新物种。Terra的两位核心创始人均有着较为光鲜的传统互联网履历,其中一人曾在微软任职,离职后创办了端对端网络共享服务工具Anyfi,另一人曾创办了韩国最早的团购网站TMON,可能是做一个基于区块链技术的金融生态的共同梦想,让两个人走到一起,并在2018年创立了这一项目。值得关注的是作为算法稳定币,UST不以法币或其他实物资产做抵押,其价值稳定机制和代币Luna关联。每铸造一个UST就必须烧掉价值一美元的Luna,Luna的套利机制保证了UST与美元的锚定。另外UST还与美国和韩国以及蒙古等国家的法币挂钩,且由此衍生出细分的稳定币。在2019年初Terra就已经成为蒙古国首个区块链支付系统。

稳定币这一关键的基础设施推出后,由Terra支持的第一个应用分布式的支付网关系统CHAI在韩国本土取得成功。截止到2021年12月底CHAI的API帮助企业整合了多达20种的支付选项,一站式打通了本地付款网关和数字以及电汇和PayPal及借记卡和信用卡等支付渠道,对于企业而言省了大量的时间和网络工程成本,这背后是CHAI远低于传统机构的手续费率。在合规问题上CHAI 拥有受韩国政府监管的法币支付网关,可连接约15家大型银行。CHAI还为普通用户提供借记卡服务。

CHAI等应用只是Terra伸向未来传统金融世界的触角,在初期官方更注重链上的DeFi应用生态。目前Terra公链上的Dapp已逾70个,并构建了较为齐全的DeFi版图,涵盖固定利率协议Anchor和Lido以及去中心化的Robinhood Mirror等等。其实提及去中心化网络支付系统不得不谈XRP。但遗憾的是在近两年逐渐去社区化以及凭遭SEC起诉和调查而错失了DeFi的这波浪潮,在2021年的牛市行情中并无存在感。当然和Terra的链上金融生态相比,应用单一的XRP也略显单薄。可见在如今的加密行业中生态布局是资本偏爱的热点,更是代表着未来想象力的话题。

其次所有的新公链都有一个共同的梦想那就是替代以太坊。他们在提供更低廉的费率基础上,更注重打磨跨链和扩容等技术,优化开发者的使用体验。而在提升跨链互操作性的行动说明Terra也有这一雄心。今年9月Terra 宣布完成Columbus 5升级,借此优化核心系统方便支持IBC的链上资产转移,这被拥趸们视作生态爆发的决定性推动力。此外此次升级的改进还有燃烧所有的铸币税和升级到 Stargate以及集成Terra 生态保险协议Ozone和Wormhole。其中 Terra 的区块链间通信IBC集成预计将提高其稳定币TerraUSD UST在整个 Cosmos 生态系统中的应用。

具体来看基于Cosmos SDK 开发的Terra可以通过启用 IBC 传输的治理提案投票,正式激活 IBC 标准。Terra 生态的用户可以跨链连接其它支持 IBC 标准的区块链网络并发送和接收资产,与Cosmos的区块链互联网的兼容性增强意味着数据可以在 Terra和其他 Cosmos 集成区块链之间共享,例如波卡和Solana甚至是以太坊。Stargate集成将Terra开放给Cosmos生态系统中数百个Dapp。总之Terra依附Cosmos使自身的跨链性得以增强。IBC 是一种互操作性协议也是Cosmos生态主要使用的通讯协议,用于在任意状态机之间传输任意数据。IBC 可用于构建广泛的跨链应用程序,包括但不限于代币转移和跨链账户以及不可替代的代币转移和预言机数据馈送。

上一期视频我们已经讨论过与波卡并称跨链双雄的Cosmos,在2021年DeFi和NFT热潮以及大牛市行情中显得格外沉寂。但是,从数据上来看Cosmos很可能是在低调布局跨链技术,毕竟这也是加密世界最具想象力的赛道之一。当Cosmos的跨链技术和生态愈发成熟,Terra公链的收益也会越大。Terra的宣发风格与Cosmos大致相似,走低调内敛路线并不热衷于营销,与波卡和Solana以及BSC和Avalanche迥异。

抛开晦涩繁琐的技术逻辑,用大把烧钱来刺激生态或许更有说服力。2021年9月Terra官方推出了价值1.5亿美元的生态激励计划,用以扶持链上的项目和开发者。从数据表现来看Terra总锁仓量的爆发也是在9月和10月左右开始的。据此判断在2021年加密行情整体走牛的背景下,以太坊公链上DeFi应用频繁外溢的过程中,BCS和Solana以及Avalanche等公链新贵在提供性价比更高的基础服务的同时,错峰推出生态奖励政策轮番吸引了大量的链上开发者,致使公链第二的宝座轮番更替。可以说Terra目前的优势地位,可能是暂时性的和周期性的。因为随着2022年美国加息预期走强,数字资产牛市可能难以为继。让我让我们可观的来讨论Terra目前面临的一些问题。

第一个方面来说UST本质上是算法稳定币,并无实物资产做抵押,因此尤其是极端行情下很容易出现价格波动,比如在5.19行情下UST的振幅远超USDT等中心化稳定币,差点导致社区分崩离析。如果币值稳定这一基本属性不保,UST将失去信用进而导致整个Terra生态的塌方。

第二个方面来说目前Terra的生态布局过度集中于DeFi领域,在更能带流量的NFT和GameFi上乏善可陈,并未孕育出知名的原生型应用,这将极大限制后续的用户增长。DeFi Llama数据显示Terra链上锁仓量排前五的协议是 Lido和Anchor以及Terraswap和Astroport及Mirror,五个 DeFi 协议总计就锁仓了接近160亿美元,占到了Terra 链上总锁仓价值的91%以上。反观BSC和波场等公链在2021年上半年就举办过几次有影响力的NFT拍卖会,并先后开通了NFT的MarketPlace。所以Terra在NFT上的行动是滞后和迟缓的。

第三个方面来说大手笔撒钱就像一针兴奋剂让Terra生态快速活泛起来,但当补贴退坡和潮水褪去后Terra能否继续高歌猛进。Terra原生的借贷利率协议Anchor的锁仓量一度冲进前十,但增长的核心因素是高达20%的利率。当资本找到更有故事性的新公链项目,Terra公链不排出最终沦为弃子。

最后第四个方面来说尽管Terra支撑的金融支付应用CHAI监管友好且发展迅猛,相较其他本土的支付巨头在规模体量上完全无法构成威胁。当然这也是区块链技术本身的不完备,以及全球商圈对分布式应用的接受程度远远不够所造成的。

#terra #cryto 

公链赛道爆火的Terra,它的优势和面临的问题?

スマートコントラクトを開発し、Terraブロックチェーンネットワークに展開します

独自のスマートコントラクトを構築することは、Web 3の開始以来存在しており、人々がブロックチェーンに展開するプログラムを構築できるようにしています。

スマートコントラクトを展開するブロックチェーンは、イーサリアムからビットコイン、さらにはそれ以上の範囲です。さらに、スマートコントラクトは連携して分散型アプリケーションを構成します。分散型アプリケーションは、Truffle、Hardhat、Embarkなどのフレームワークで開発できます。

この記事では、スマートコントラクトを開発し、それらをイーサリアムに似たTerraブロックチェーンネットワークにデプロイする方法を見ていきます。

Terraの基本的な概要

読む前にTerraについて注意すべき点がいくつかあります。

また、Terraのコンセンサスは、TendermintBFTを使用したプルーフオブステークアルゴリズムであることに注意してください。これにより、保有者は取引を検証するための担保としてトークンを賭けることができます。その後、賭けたトークンの量に応じて報酬が与えられます。

LUNAはTerraの暗号通貨であり、プルーフオブステークブロックチェーンを強化するために使用されることを知っておくことも重要です。このブロックチェーンは、アルゴリズムを拡張して供給を減らすことにより、価格の安定性を提供します。

詳細については、こちらのドキュメントを読みになることをお勧めします。この記事の主な焦点は、スマートコントラクトをこのブロックチェーンプロトコルにデプロイする方法です。

そして最後に、Terraブロックチェーンは、ビットコインやイーサリアムよりも高速に、トランザクションのバッチを数秒で完了する強力で強力なコンセンサスメカニズムを誇っています。

要件と開発の基本

Terraプロトコルを使用してスマートコントラクトを構築および展開するために必要な要件を見てみましょう。

  • Rustプログラミング言語の知識
  • Terraエコシステムに精通している
  • コンピューターにインストールされているDocker
  • テラコア
  • LocalTerra

ただし、上記の要件がなくても心配する必要はありません。すべてをカバーします。ただし、Terraチームによると、最後の要件の1つは、従来の金融を混乱させる/混乱させることを望んでいることです。

環境設定

始める前にインストールする必要があるものがいくつかあります。このインストールは、契約書を作成するときにTerraのローカルテストネットに接続し、の最新バージョンを提供するのに役立ちますterradTerraコアでterrad動作します。

Rustをまだインストールしていない場合は、インストールする必要があります。

まず、Terra Coreをインストールしましょう。これには、最初にGoをインストールする必要があります。これを行うには、このリンク使用してGoをダウンロードし、以下を確認します。

➜  ~ go version
go version go1.17 darwin/amd64

TerraCoreを使用するために必要なバージョンv1.17 +に移行します。

TerraCoreのインストール

GitHubからリポジトリのクローンを作成して、TerraCoreをインストールします。次に、最新リリースのメインブランチを確認します。

$ git clone https://github.com/terra-money/core terra-core
$ cd terra-core
$ git checkout main

次に、Terra Coreをインストールして取得しますterrad。これは、Terraノードと対話するための実行可能ファイルとして機能します。

$ make install

次に、正常にインストールされたことを確認します。

$ terrad version --long

出力は次のようになります。

name: terra
server_name: terrad
version: 0.5.12-1-gd411ae7
commit: d411ae7a276e7eaada72973a640dcab69825163f
build_tags: netgo,ledger
go: go version go1.17 darwin/amd64

LocalTerraのインストール

LocalTerraは、開発中にスマートコントラクトをテストするためのテストネットになります。ローカルテストネットは、WebAssembly統合で構成されています。 LocalTerraはコンテナ化されているため、LocalTerraを起動するには、Dockerを使用してdocker-composeセットアップする必要があります。

$ git clone --depth 1 https://www.github.com/terra-money/LocalTerra
$ cd LocalTerra

Dockerをバックグラウンドで実行している状態で、次のコマンドを実行します。

$ docker-構成する

以下の応答が表示されます。これはログです。

 11:25PM INF Timed out dur=4955.7669 height=5 module=consensus round=0 step=1
terrad_1         | 11:25PM INF received proposal module=consensus proposal={"Type":32,"block_id":{"hash":"54D9C757E9AA84E0F5AAA736E6EED3D83F364A3A62FDC625970539CA81DFA86E","parts":{"hash":"2517579A126AC2BF6EB9EB6274FAE6748D14115C91FC59FE3A2AF5F061A12740","total":1}},"height":5,"pol_round":-1,"round":0,"signature":"AMxXngubsUHyterTZuZsiLgY0olPDpdpgjMIRZ9L59UR9+JngC93xO63yTxwE0kQLp2HdZ99G8M4ATchS7d1CA==","timestamp":"2021-12-16T23:25:00.8000592Z"}
terrad_1         | 11:25PM INF received complete proposal block hash=54D9C757E9AA84E0F5AAA736E6EED3D83F364A3A62FDC625970539CA81DFA86E height=5 module=consensus
terrad_1         | 11:25PM INF finalizing commit of block hash=54D9C757E9AA84E0F5AAA736E6EED3D83F364A3A62FDC625970539CA81DFA86E height=5 module=consensus num_txs=0 root=84C2F2EF6B7FC8B3ACED8B2B0D2921D649F13CE54C5AB5B032DE988D1392E0FD
terrad_1         | 11:25PM INF minted coins from module account amount=226569846uluna from=mint module=x/bank
terrad_1         | 11:25PM INF executed block height=5 module=state num_invalid_txs=0 num_valid_txs=0
terrad_1         | 11:25PM INF commit synced commit=436F6D6D697449447B5B32382031303020373220323137203234312038352031363320313520313530203137382031353820323235203133312032343620313538203235322031333420313238203134392031383220323033203131372039382031333420312035382032333720323120333620313534203136203134335D3A357D
terrad_1         | 11:25PM INF committed state app_hash=1C6448D9F155A30F96B29EE183F69EFC868095B6CB756286013AED15249A108F height=5 module=state num_txs=0
terrad_1         | 11:25PM INF indexed block height=5 module=txindex
terrad_1         | 11:25PM INF Ensure peers module=pex numDialing=0 numInPeers=0 numOutPeers=0 numToDial=10
terrad_1         | 11:25PM INF No addresses to dial. Falling back to seeds module=pex
terrad_1         | 11:25PM INF Timed out dur=4975.4085 height=6 module=consensus round=0 step=1
terrad_1         | 11:25PM INF received proposal module=consensus proposal={"Type":32,"block_id":{"hash":"5FE8526C43C0B32BEF011299D67FDA44DBD625E0B69836D175C25C1F914DD06E","parts":{"hash":"BE583EC25B30F52E652FA28DEAB869D98602B3FB82CD0D9C80ADF96A210CC8D4","total":1}},"height":6,"pol_round":-1,"round":0,"signature":"Bx3WaDl3hhR9IkDjXRa+dXkSIK0Tezl07gZhDm4RXyJyHq0oriAkQD23Q9+ly1+cFhGIdKF3hyvH3GcjCNLvAQ==","timestamp":"2021-12-16T23:25:05.823444Z"}

これで、LocalTerraネットワークに接続されました。接続するポート番号は次のとおりです。

Rustのインストール

RustはTerraがスマートコントラクトを使用および作成するために選択したものです。RustはWebAssemblyにコンパイルでき、WebAssemblyツールはTerra用に十分に成熟して構築されているためです。

MacOSまたはLinuxのようなOSにRustをインストールするには、次のコマンドを実行します。

$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Windowsを使用している場合は、このリンクを使用してください

正常にインストールされたらwasm32-unknown-unknown、コンパイルのターゲットを追加する必要があります。

$ rustup target add wasm32-unknown-unknown

最後に、cargo-generateCosmWasmスマートコントラクトテンプレートをスキャフォールディングし、スマートコントラクトcargo-run-scriptを最適化するためにインストールしましょう。

$ cargo install cargo-generate --features vendored-openssl
$ cargo install cargo-run-script

ついにインストールが完了しました🙂

Terraでスマートコントラクトを作成して探索する

LocalTerraネットワークが実行され、私たちを待っているので、私たちは少しスマートコントラクトを作成し、それらを展開する準備ができています、そして私たちはその日のために終わりました!

インストールしたのでcargo-generate、作業プロジェクトをすばやく足場にすることができます。これは、コントラクトを作成するためのフォルダー構造に役立ちます。これを行うには、次のコマンドを使用します。

$ cargo generate --git https://github.com/CosmWasm/cw-template.git --name PROJECT_NAME

の場合PROJECT_NAME、プロジェクトの名前を付ける必要があります。以下は、前のコマンドを実行した後に取得する必要があるものです。

Vectormikes-MacBook-Pro:Projects macbookpro$ cargo generate --git https://github.com/CosmWasm/cw-template.git --name terra-demo
   Generating template ...
[ 1/34]   Done: .cargo/config
[ 2/34]   Done: .cargo
[ 3/34]   Skipped: .circleci/config.yml
[ 4/34]   Done: .circleci
[ 1/34]   Done: .cargo/config
[ 2/34]   Done: .cargo
[ 3/34]   Skipped: .circleci/config.yml
[ 4/34]   Done: .circleci
[ 5/34]   Done: .editorconfig
[ 6/34]   Done: .github/workflows/Basic.yml
[ 7/34]   Done: .github/workflows
[ 8/34]   Done: .github
[ 9/34]   Done: .gitignore
[10/34]   Done: .gitpod.Dockerfile
[11/34]   Done: .gitpod.yml
[ 1/34]   Done: .cargo/config
[ 2/34]   Done: .cargo
[ 3/34]   Skipped: .circleci/config.yml
[ 4/34]   Done: .circleci
[ 5/34]   Done: .editorconfig
[ 6/34]   Done: .github/workflows/Basic.yml
[ 7/34]   Done: .github/workflows
[ 8/34]   Done: .github
[ 9/34]   Done: .gitignore
[10/34]   Done: .gitpod.Dockerfile
[11/34]   Done: .gitpod.yml
[12/34]   Done: Cargo.lock
[13/34]   Done: Cargo.toml
[14/34]   Done: Developing.md
[15/34]   Done: Importing.md
[16/34]   Done: LICENSE
[17/34]   Done: NOTICE
[18/34]   Done: Publishing.md
[19/34]   Done: README.md
[20/34]   Done: examples/schema.rs
[21/34]   Done: examples
[22/34]   Done: rustfmt.toml
[23/34]   Done: schema/count_response.json
[24/34]   Done: schema/execute_msg.json
[25/34]   Done: schema/instantiate_msg.json
[26/34]   Done: schema/query_msg.json
[27/34]   Done: schema/state.json
[28/34]   Done: schema
[29/34]   Done: src/contract.rs
[30/34]   Done: src/error.rs
[31/34]   Done: src/lib.rs
[32/34]   Done: src/msg.rs
[33/34]   Done: src/state.rs
[34/34]   Done: src
   Moving generated files into: `/Users/macbookpro/Desktop/Projects/terra-demo`...
   Done! New project created /Users/macbookpro/Desktop/Projects/terra-demo

見るとsrc/msg.rs、ファイル、我々は我々のスマート契約に送信できるメッセージの3種類を見ることができます。まず、これにはInstantiateMsg、スマートコントラクトの状態を設定するが含まれます。つまり、スマートコントラクトがスピンアップされたときに初期状態を指定する必要があります。

2つ目ExecuteMsgは、ブロックチェーンへのメッセージの投稿など、状態変化に対するアクションを実行するメッセージです。そして最後に、それQueryMsgはそれが聞こえる通りです:それはチェーンへのクエリとして機能し、そこからデータを取得します。

これらがコード内で使用されている方法を見てみましょう。

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
    pub count: i32,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
    Increment {},
    Reset { count: i32 },
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    // GetCount returns the current count as a json-encoded number
    GetCount {},
}
// We define a custom struct for each query response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct CountResponse {
    pub count: i32,
}

契約に移る前にStatesrc/state.rsファイル内にあるインターフェースを見てみましょう。

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use cosmwasm_std::Addr;
use cw_storage_plus::Item;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct State {
    pub count: i32,
    pub owner: Addr,
}
pub const STATE: Item<State> = Item::new("state");

私たちの構造体は、State含んでいなければならないcounti32ownerのをAddr。Terraによると、Key-ValueストレージであるTerraのアクティブなLevelDBのために、私たちの状態は永続的です。

それを念頭に置いて、私たちの契約はsrc/contract.rsファイルにあります:

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    msg: InstantiateMsg,
) -> Result<Response, ContractError> {
    let state = State {
        count: msg.count,
        owner: info.sender.clone(),
    };
    set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
    STATE.save(deps.storage, &state)?;
    Ok(Response::new()
        .add_attribute("method", "instantiate")
        .add_attribute("owner", info.sender)
        .add_attribute("count", msg.count.to_string()))
}

このinstantiateメソッドは、サポートするインターフェースとともに、4つの引数、deps_ 、、、およびを想定しています。次に、期待される結果または期待される結果を期待します。envinfomsgResponseContractError

ここではContractErrorsrc/error.rsファイルで定義しました。

use cosmwasm_std::StdError;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ContractError {
    #[error("{0}")]
    Std(#[from] StdError),
    #[error("Unauthorized")]
    Unauthorized {},
    // Add any other custom errors you like here.
    // Look at https://docs.rs/thiserror/1.0.21/thiserror/ for details.
}

のような他のいくつかのインターフェースResponseもからインポートされましたcosmwasm_std

#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use cw2::set_contract_version;

次に、メソッドのために、我々はまた、持っているexecutequery私たちの契約で:

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    msg: ExecuteMsg,
) -> Result<Response, ContractError> {
    match msg {
        ExecuteMsg::Increment {} => try_increment(deps),
        ExecuteMsg::Reset { count } => try_reset(deps, info, count),
    }
}

pub fn try_increment(deps: DepsMut) -> Result<Response, ContractError> {
    STATE.update(deps.storage, |mut state| -> Result<_, ContractError> {
        state.count += 1;
        Ok(state)
    })?;
    Ok(Response::new().add_attribute("method", "try_increment"))
}
pub fn try_reset(deps: DepsMut, info: MessageInfo, count: i32) -> Result<Response, ContractError> {
    STATE.update(deps.storage, |mut state| -> Result<_, ContractError> {
        if info.sender != state.owner {
            return Err(ContractError::Unauthorized {});
        }
        state.count = count;
        Ok(state)
    })?;
    Ok(Response::new().add_attribute("method", "reset"))
}

ここで、try_incrementでカウント状態を増大させる1、及びtry_resetカウント状態をリセットする、に使用される関数であるexecute関数。

最後に、queryストレージから状態または情報を取得するカウントは、以下で実行されます。

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
    match msg {
        QueryMsg::GetCount {} => to_binary(&query_count(deps)?),
    }
}
fn query_count(deps: Deps) -> StdResult<CountResponse> {
    let state = STATE.load(deps.storage)?;
    Ok(CountResponse { count: state.count })
}

スマートコントラクトをLocalTerraにアップロードする

これで、コンパイル中にエラーをチェックするスマートコントラクトを構築して、修正できるようになりました。そのために、次のコマンドを実行します。

$ cargo wasm

そしてcargo-run-script、ビルドの最適化を支援するためにインストールしたのと同じように、今はそれを使用する必要があります。

$カーゴラン-スクリプト最適化

プロジェクトディレクトリに、のコードがartifacts/terra_demo.wasm表示されます。これはまもなくLocalTerraにアップロードされます。これで、ローカルテストネット名とノードモニカを作成できます。

$ terrad init --chain-id=<testnet_name> <node_moniker>

これにより、ニーモニックを入力するように求められます。

 $ terrad keys add <account_name>

Terraによると、以下のニーモニックを持つアカウントがネットワーク上の唯一のバリデーターです。

満足する調整材高購入授業料スツール信仰あなたが気づいていないフィードドメインライセンスが上司に課す人間の熱心な帽子の家賃は夜明けを楽しむ

次に、コードをTerraネットワークにアップロードできます。

terrad tx wasm store artifacts/terra_demo.wasm --from demo --chain-id=localterra --gas=auto --fees=100000uluna --broadcast-mode=block

これにより、LocalTerraにプッシュできるように「yes」と入力する必要がある許可が求められます。成功すると、契約はLocalTerraネットワークにブロードキャストされます。

結論

Terraのスマートコントラクトの表面をかじり始めたばかりです。これは、TerraプロトコルでdAppを構築する方法の概要のみを示しているはずです。

このプロトコルに基づいて構築することを強くお勧めします。これは、その活発に成長しているユーザーベースと、LUNAを含むTerraステーブルコインが支払いソリューションに追加されているためです。これは朗報です。

また、高速で効率的なコンセンサスがあり、将来のリリースでより効率的になります。

リン:https//blog.logrocket.com/developing-terra-smart-contracts/

#terra  #smart 

スマートコントラクトを開発し、Terraブロックチェーンネットワークに展開します