cosmwasm: terra2 support
Co-authored-by: Csongor Kiss <ckiss@jumptrading.com>
This commit is contained in:
parent
13780dba51
commit
db0fc219aa
6
Tiltfile
6
Tiltfile
|
@ -580,8 +580,8 @@ k8s_yaml_with_ns("devnet/terra2-devnet.yaml")
|
|||
k8s_resource(
|
||||
"terra2-terrad",
|
||||
port_forwards = [
|
||||
port_forward(26657, name = "Terra 2 RPC [:26657]", host = webHost),
|
||||
port_forward(1317, name = "Terra 2 LCD [:1317]", host = webHost),
|
||||
port_forward(26658, container_port = 26657, name = "Terra 2 RPC [:26658]", host = webHost),
|
||||
port_forward(1318, container_port = 1317, name = "Terra 2 LCD [:1318]", host = webHost),
|
||||
],
|
||||
resource_deps = ["const-gen"],
|
||||
labels = ["terra2"],
|
||||
|
@ -597,7 +597,7 @@ k8s_resource(
|
|||
k8s_resource(
|
||||
"terra2-fcd",
|
||||
resource_deps = ["terra2-terrad", "terra2-postgres"],
|
||||
port_forwards = [port_forward(3060, name = "Terra 2 FCD [:3060]", host = webHost)],
|
||||
port_forwards = [port_forward(3061, container_port = 3060, name = "Terra 2 FCD [:3061]", host = webHost)],
|
||||
labels = ["terra2"],
|
||||
trigger_mode = trigger_mode,
|
||||
)
|
||||
|
|
|
@ -3,7 +3,7 @@ import yargs from "yargs";
|
|||
|
||||
import { hideBin } from "yargs/helpers";
|
||||
|
||||
import { setDefaultWasm } from "@certusone/wormhole-sdk";
|
||||
import { isTerraChain, setDefaultWasm } from "@certusone/wormhole-sdk";
|
||||
import { execute_governance_solana } from "./solana";
|
||||
import { execute_governance_evm } from "./evm";
|
||||
import { execute_governance_terra } from "./terra";
|
||||
|
@ -271,7 +271,7 @@ yargs(hideBin(process.argv))
|
|||
);
|
||||
} else if (isEVMChain(chain)) {
|
||||
await execute_governance_evm(parsed_vaa.payload, buf, network, chain);
|
||||
} else if (chain === "terra") {
|
||||
} else if (isTerraChain(chain)) {
|
||||
await execute_governance_terra(parsed_vaa.payload, buf, network);
|
||||
} else if (chain === "solana") {
|
||||
await execute_governance_solana(parsed_vaa, buf, network);
|
||||
|
|
|
@ -90,6 +90,10 @@ const MAINNET = {
|
|||
rpc: undefined,
|
||||
key: undefined,
|
||||
},
|
||||
terra2: {
|
||||
rpc: undefined,
|
||||
key: undefined,
|
||||
},
|
||||
ropsten: {
|
||||
rpc: `https://ropsten.infura.io/v3/${get_env_var("INFURA_KEY")}`,
|
||||
key: get_env_var("ETH_KEY"),
|
||||
|
@ -170,6 +174,10 @@ const TESTNET = {
|
|||
rpc: "https://proxy.devnet.neonlabs.org/solana",
|
||||
key: get_env_var("ETH_KEY"),
|
||||
},
|
||||
terra2: {
|
||||
rpc: undefined,
|
||||
key: undefined,
|
||||
},
|
||||
ropsten: {
|
||||
rpc: `https://ropsten.infura.io/v3/${get_env_var("INFURA_KEY")}`,
|
||||
key: get_env_var("ETH_KEY"),
|
||||
|
@ -250,6 +258,10 @@ const DEVNET = {
|
|||
rpc: undefined,
|
||||
key: undefined,
|
||||
},
|
||||
terra2: {
|
||||
rpc: undefined,
|
||||
key: undefined,
|
||||
},
|
||||
ropsten: {
|
||||
rpc: undefined,
|
||||
key: undefined,
|
||||
|
|
|
@ -9,7 +9,7 @@
|
|||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@celo-tools/celo-ethers-wrapper": "^0.1.0",
|
||||
"@certusone/wormhole-sdk": "^0.3.8",
|
||||
"@certusone/wormhole-sdk": "^0.4.1",
|
||||
"@solana/web3.js": "^1.22.0",
|
||||
"@terra-money/terra.js": "^1.8.9",
|
||||
"axios": "^0.24.0",
|
||||
|
@ -542,14 +542,14 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@certusone/wormhole-sdk": {
|
||||
"version": "0.3.8",
|
||||
"resolved": "https://registry.npmjs.org/@certusone/wormhole-sdk/-/wormhole-sdk-0.3.8.tgz",
|
||||
"integrity": "sha512-XHWKRqYo+Euj8DNWPLM3j5cXAqVkp4QtmpYqheLqO3hQLIc5MvyHZfXHxfAq0gmrdQT89xP5Dq8Q3uLGtq07QQ==",
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@certusone/wormhole-sdk/-/wormhole-sdk-0.4.1.tgz",
|
||||
"integrity": "sha512-kScSlYtdOY+xlJNMBSkze16umYIw+/yI2TRQ1qY27Gnzqwes4Fl1z+WJEioO3pCH62SYLCYlme16xjL50Y7b+A==",
|
||||
"dependencies": {
|
||||
"@improbable-eng/grpc-web": "^0.14.0",
|
||||
"@solana/spl-token": "^0.1.8",
|
||||
"@solana/web3.js": "^1.24.0",
|
||||
"@terra-money/terra.js": "^3.0.7",
|
||||
"@terra-money/terra.js": "^3.1.3",
|
||||
"algosdk": "^1.15.0",
|
||||
"axios": "^0.24.0",
|
||||
"bech32": "^2.0.0",
|
||||
|
@ -10963,14 +10963,14 @@
|
|||
"requires": {}
|
||||
},
|
||||
"@certusone/wormhole-sdk": {
|
||||
"version": "0.3.8",
|
||||
"resolved": "https://registry.npmjs.org/@certusone/wormhole-sdk/-/wormhole-sdk-0.3.8.tgz",
|
||||
"integrity": "sha512-XHWKRqYo+Euj8DNWPLM3j5cXAqVkp4QtmpYqheLqO3hQLIc5MvyHZfXHxfAq0gmrdQT89xP5Dq8Q3uLGtq07QQ==",
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@certusone/wormhole-sdk/-/wormhole-sdk-0.4.1.tgz",
|
||||
"integrity": "sha512-kScSlYtdOY+xlJNMBSkze16umYIw+/yI2TRQ1qY27Gnzqwes4Fl1z+WJEioO3pCH62SYLCYlme16xjL50Y7b+A==",
|
||||
"requires": {
|
||||
"@improbable-eng/grpc-web": "^0.14.0",
|
||||
"@solana/spl-token": "^0.1.8",
|
||||
"@solana/web3.js": "^1.24.0",
|
||||
"@terra-money/terra.js": "^3.0.7",
|
||||
"@terra-money/terra.js": "^3.1.3",
|
||||
"algosdk": "^1.15.0",
|
||||
"axios": "^0.24.0",
|
||||
"bech32": "^2.0.0",
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@celo-tools/celo-ethers-wrapper": "^0.1.0",
|
||||
"@certusone/wormhole-sdk": "^0.3.8",
|
||||
"@certusone/wormhole-sdk": "^0.4.1",
|
||||
"@solana/web3.js": "^1.22.0",
|
||||
"@terra-money/terra.js": "^1.8.9",
|
||||
"axios": "^0.24.0",
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -3,10 +3,6 @@ members = [
|
|||
"contracts/cw20-wrapped",
|
||||
"contracts/wormhole",
|
||||
"contracts/token-bridge",
|
||||
"contracts/nft-bridge",
|
||||
"contracts/cw721-wrapped",
|
||||
"packages/cw721",
|
||||
"contracts/cw721-base",
|
||||
"contracts/mock-bridge-integration",
|
||||
]
|
||||
|
||||
|
|
|
@ -6,14 +6,13 @@ FROM cosmwasm/workspace-optimizer:0.12.6@sha256:e6565a5e87c830ef3e8775a9035006b3
|
|||
COPY Cargo.lock /code/
|
||||
COPY Cargo.toml /code/
|
||||
COPY contracts /code/contracts
|
||||
COPY packages /code/packages
|
||||
|
||||
# Support additional root CAs
|
||||
COPY README.md cert.pem* /certs/
|
||||
# Alpine
|
||||
RUN if [ -e /certs/cert.pem ]; then cp /certs/cert.pem /etc/ssl/cert.pem; fi
|
||||
|
||||
RUN optimize_workspace.sh
|
||||
RUN --mount=type=cache,target=/code/target,id=cosmwasm_target --mount=type=cache,target=/usr/local/cargo/registry optimize_workspace.sh
|
||||
|
||||
FROM scratch as artifacts
|
||||
COPY --from=builder /code/artifacts /
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
bridge_SOURCE=wormhole
|
||||
token_bridge_SOURCE=token_bridge_terra
|
||||
nft_bridge_SOURCE=nft_bridge
|
||||
|
||||
SOURCE_FILES=$(shell find . -name "*.rs" -or -name "*.lock" -or -name "*.toml" | grep -v target)
|
||||
|
||||
|
@ -36,10 +35,6 @@ deploy/bridge: bridge-code-id-$(NETWORK).txt
|
|||
## Deploy token bridge
|
||||
deploy/token_bridge: token_bridge-code-id-$(NETWORK).txt
|
||||
|
||||
.PHONY: deploy/nft_bridge
|
||||
## Deploy NFT bridge
|
||||
deploy/nft_bridge: nft_bridge-code-id-$(NETWORK).txt
|
||||
|
||||
%-code-id-$(NETWORK).txt: check-network tools/node_modules payer-$(NETWORK).json artifacts
|
||||
@echo "Deploying artifacts/$($*_SOURCE).wasm on $(NETWORK)"
|
||||
@node tools/deploy_single.js \
|
||||
|
@ -54,12 +49,7 @@ tools/node_modules: tools/package-lock.json
|
|||
cd tools && npm ci
|
||||
|
||||
LocalTerra:
|
||||
mkdir LocalTerra && \
|
||||
cd LocalTerra && \
|
||||
git init && \
|
||||
git remote add origin https://www.github.com/terra-money/LocalTerra.git && \
|
||||
git fetch --depth 1 origin 958ff795f261f5ff2efc7b56604e2434eb76f7c4 && \
|
||||
git checkout FETCH_HEAD
|
||||
git clone --depth 1 https://www.github.com/terra-money/LocalTerra
|
||||
|
||||
test/node_modules: test/package-lock.json
|
||||
cd test && npm ci
|
||||
|
@ -67,8 +57,8 @@ test/node_modules: test/package-lock.json
|
|||
.PHONY: unit-test
|
||||
## Run unit tests
|
||||
unit-test:
|
||||
cargo test -p wormhole-bridge-terra
|
||||
cargo test -p token-bridge-terra
|
||||
cargo test -p wormhole-bridge-terra-2
|
||||
cargo test -p token-bridge-terra-2
|
||||
|
||||
.PHONY: test
|
||||
## Run unit and integration tests
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
[package]
|
||||
name = "cw20-wrapped"
|
||||
name = "cw20-wrapped-2"
|
||||
version = "0.1.0"
|
||||
authors = ["Yuriy Savchenko <yuriy.savchenko@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
@ -14,12 +14,12 @@ backtraces = ["cosmwasm-std/backtraces"]
|
|||
library = []
|
||||
|
||||
[dependencies]
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
cosmwasm-storage = { version = "0.16.0" }
|
||||
schemars = "0.8.1"
|
||||
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
|
||||
cw2 = { version = "0.8.0" }
|
||||
cw20 = { version = "0.8.0" }
|
||||
cw20-legacy = { version = "0.2.0", features = ["library"]}
|
||||
cw-storage-plus = { version = "0.8.0" }
|
||||
thiserror = { version = "1.0.20" }
|
||||
cosmwasm-std = { version = "1.0.0" }
|
||||
cosmwasm-storage = { version = "1.0.0" }
|
||||
schemars = "0.8.8"
|
||||
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
|
||||
cw2 = { version = "0.13.2" }
|
||||
cw20 = { version = "0.13.2" }
|
||||
cw20-base = { version = "0.13.2", features = ["library"] }
|
||||
cw-storage-plus = { version = "0.13.2" }
|
||||
thiserror = { version = "1.0.31" }
|
||||
|
|
|
@ -17,7 +17,7 @@ use cosmwasm_std::{
|
|||
use cosmwasm_std::entry_point;
|
||||
|
||||
use cw2::set_contract_version;
|
||||
use cw20_legacy::{
|
||||
use cw20_base::{
|
||||
allowances::{
|
||||
execute_burn_from,
|
||||
execute_decrease_allowance,
|
||||
|
@ -80,7 +80,7 @@ pub fn instantiate(
|
|||
total_supply: Uint128::new(0),
|
||||
// set creator as minter
|
||||
mint: Some(MinterData {
|
||||
minter: deps.api.addr_canonicalize(info.sender.as_str())?,
|
||||
minter: deps.api.addr_validate(info.sender.as_str())?,
|
||||
cap: None,
|
||||
}),
|
||||
};
|
||||
|
|
|
@ -17,7 +17,7 @@ use cosmwasm_std::{
|
|||
};
|
||||
use cosmwasm_storage::to_length_prefixed;
|
||||
use cw20::TokenInfoResponse;
|
||||
use cw20_wrapped::{
|
||||
use cw20_wrapped_2::{
|
||||
contract::{
|
||||
execute,
|
||||
instantiate,
|
||||
|
@ -49,7 +49,7 @@ fn get_wrapped_asset_info<S: Storage>(storage: &S) -> WrappedAssetInfo {
|
|||
}
|
||||
|
||||
fn do_init() -> OwnedDeps<MockStorage, MockApi, MockQuerier> {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let mut deps = mock_dependencies();
|
||||
let init_msg = InstantiateMsg {
|
||||
name: "Integers".into(),
|
||||
symbol: "INT".into(),
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
[alias]
|
||||
wasm = "build --release --target wasm32-unknown-unknown"
|
||||
wasm-debug = "build --target wasm32-unknown-unknown"
|
||||
unit-test = "test --lib"
|
||||
schema = "run --example schema"
|
|
@ -1,38 +0,0 @@
|
|||
[package]
|
||||
name = "cw721-base"
|
||||
version = "0.10.1"
|
||||
authors = ["Ethan Frey <ethanfrey@users.noreply.github.com>"]
|
||||
edition = "2018"
|
||||
description = "Basic implementation cw721 NFTs"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/CosmWasm/cw-nfts"
|
||||
homepage = "https://cosmwasm.com"
|
||||
documentation = "https://docs.cosmwasm.com"
|
||||
|
||||
exclude = [
|
||||
# Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication.
|
||||
"artifacts/*",
|
||||
]
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
# for more explicit tests, cargo test --features=backtraces
|
||||
backtraces = ["cosmwasm-std/backtraces"]
|
||||
# use library feature to disable all instantiate/execute/query exports
|
||||
library = []
|
||||
|
||||
[dependencies]
|
||||
cw0 = { version = "0.8.0" }
|
||||
cw2 = { version = "0.8.0" }
|
||||
cw721 = { path = "../../packages/cw721", version = "0.10.1" }
|
||||
cw-storage-plus = { version = "0.8.0" }
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
schemars = "0.8.6"
|
||||
serde = { version = "1.0.130", default-features = false, features = ["derive"] }
|
||||
thiserror = { version = "1.0.30" }
|
||||
|
||||
[dev-dependencies]
|
||||
cosmwasm-schema = { version = "1.0.0-beta2" }
|
|
@ -1,14 +0,0 @@
|
|||
Cw721_base
|
||||
Copyright (C) 2020-2021 Confio OÜ
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License 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.
|
|
@ -1,71 +0,0 @@
|
|||
# Cw721 Basic
|
||||
|
||||
This is a basic implementation of a cw721 NFT contract. It implements
|
||||
the [CW721 spec](../../packages/cw721/README.md) and is designed to
|
||||
be deployed as is, or imported into other contracts to easily build
|
||||
cw721-compatible NFTs with custom logic.
|
||||
|
||||
Implements:
|
||||
|
||||
- [x] CW721 Base
|
||||
- [x] Metadata extension
|
||||
- [ ] Enumerable extension (AllTokens done, but not Tokens - requires [#81](https://github.com/CosmWasm/cw-plus/issues/81))
|
||||
|
||||
## Implementation
|
||||
|
||||
The `ExecuteMsg` and `QueryMsg` implementations follow the [CW721 spec](../../packages/cw721/README.md) and are described there.
|
||||
Beyond that, we make a few additions:
|
||||
|
||||
* `InstantiateMsg` takes name and symbol (for metadata), as well as a **Minter** address. This is a special address that has full
|
||||
power to mint new NFTs (but not modify existing ones)
|
||||
* `ExecuteMsg::Mint{token_id, owner, token_uri}` - creates a new token with given owner and (optional) metadata. It can only be called by
|
||||
the Minter set in `instantiate`.
|
||||
* `QueryMsg::Minter{}` - returns the minter address for this contract.
|
||||
|
||||
It requires all tokens to have defined metadata in the standard format (with no extensions). For generic NFTs this may
|
||||
often be enough.
|
||||
|
||||
The *Minter* can either be an external actor (eg. web server, using PubKey) or another contract. If you just want to customize
|
||||
the minting behavior but not other functionality, you could extend this contract (importing code and wiring it together)
|
||||
or just create a custom contract as the owner and use that contract to Mint.
|
||||
|
||||
If provided, it is expected that the _token_uri_ points to a JSON file following the [ERC721 Metadata JSON Schema](https://eips.ethereum.org/EIPS/eip-721).
|
||||
|
||||
## Running this contract
|
||||
|
||||
You will need Rust 1.44.1+ with `wasm32-unknown-unknown` target installed.
|
||||
|
||||
You can run unit tests on this via:
|
||||
|
||||
`cargo test`
|
||||
|
||||
Once you are happy with the content, you can compile it to wasm via:
|
||||
|
||||
```
|
||||
RUSTFLAGS='-C link-arg=-s' cargo wasm
|
||||
cp ../../target/wasm32-unknown-unknown/release/cw721_base.wasm .
|
||||
ls -l cw721_base.wasm
|
||||
sha256sum cw721_base.wasm
|
||||
```
|
||||
|
||||
Or for a production-ready (optimized) build, run a build command in the
|
||||
the repository root: https://github.com/CosmWasm/cw-plus#compiling.
|
||||
|
||||
## Importing this contract
|
||||
|
||||
You can also import much of the logic of this contract to build another
|
||||
CW721-compliant contract, such as tradable names, crypto kitties,
|
||||
or tokenized real estate.
|
||||
|
||||
Basically, you just need to write your handle function and import
|
||||
`cw721_base::contract::handle_transfer`, etc and dispatch to them.
|
||||
This allows you to use custom `ExecuteMsg` and `QueryMsg` with your additional
|
||||
calls, but then use the underlying implementation for the standard cw721
|
||||
messages you want to support. The same with `QueryMsg`. You will most
|
||||
likely want to write a custom, domain-specific `instantiate`.
|
||||
|
||||
**TODO: add example when written**
|
||||
|
||||
For now, you can look at [`cw721-staking`](../cw721-staking/README.md)
|
||||
for an example of how to "inherit" cw721 functionality and combine it with custom logic.
|
||||
The process is similar for cw721.
|
|
@ -1,39 +0,0 @@
|
|||
use std::env::current_dir;
|
||||
use std::fs::create_dir_all;
|
||||
|
||||
use cosmwasm_schema::{export_schema, export_schema_with_title, remove_schemas, schema_for};
|
||||
|
||||
use cw721::{
|
||||
AllNftInfoResponse, ApprovalResponse, ApprovalsResponse, ContractInfoResponse, NftInfoResponse,
|
||||
NumTokensResponse, OperatorsResponse, OwnerOfResponse, TokensResponse,
|
||||
};
|
||||
use cw721_base::{ExecuteMsg, Extension, InstantiateMsg, MinterResponse, QueryMsg};
|
||||
|
||||
fn main() {
|
||||
let mut out_dir = current_dir().unwrap();
|
||||
out_dir.push("schema");
|
||||
create_dir_all(&out_dir).unwrap();
|
||||
remove_schemas(&out_dir).unwrap();
|
||||
|
||||
export_schema(&schema_for!(InstantiateMsg), &out_dir);
|
||||
export_schema_with_title(&schema_for!(ExecuteMsg<Extension>), &out_dir, "ExecuteMsg");
|
||||
export_schema(&schema_for!(QueryMsg), &out_dir);
|
||||
export_schema_with_title(
|
||||
&schema_for!(AllNftInfoResponse<Extension>),
|
||||
&out_dir,
|
||||
"AllNftInfoResponse",
|
||||
);
|
||||
export_schema(&schema_for!(ApprovalResponse), &out_dir);
|
||||
export_schema(&schema_for!(ApprovalsResponse), &out_dir);
|
||||
export_schema(&schema_for!(OperatorsResponse), &out_dir);
|
||||
export_schema(&schema_for!(ContractInfoResponse), &out_dir);
|
||||
export_schema(&schema_for!(MinterResponse), &out_dir);
|
||||
export_schema_with_title(
|
||||
&schema_for!(NftInfoResponse<Extension>),
|
||||
&out_dir,
|
||||
"NftInfoResponse",
|
||||
);
|
||||
export_schema(&schema_for!(NumTokensResponse), &out_dir);
|
||||
export_schema(&schema_for!(OwnerOfResponse), &out_dir);
|
||||
export_schema(&schema_for!(TokensResponse), &out_dir);
|
||||
}
|
|
@ -1,393 +0,0 @@
|
|||
import axios from "axios";
|
||||
import fs from "fs";
|
||||
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
|
||||
import { GasPrice, calculateFee, StdFee } from "@cosmjs/stargate";
|
||||
import { DirectSecp256k1HdWallet, makeCosmoshubPath } from "@cosmjs/proto-signing";
|
||||
import { Slip10RawIndex } from "@cosmjs/crypto";
|
||||
import path from "path";
|
||||
/*
|
||||
* This is a set of helpers meant for use with @cosmjs/cli
|
||||
* With these you can easily use the cw721 contract without worrying about forming messages and parsing queries.
|
||||
*
|
||||
* Usage: npx @cosmjs/cli@^0.26 --init https://raw.githubusercontent.com/CosmWasm/cosmwasm-plus/master/contracts/cw721-base/helpers.ts
|
||||
*
|
||||
* Create a client:
|
||||
* const [addr, client] = await useOptions(pebblenetOptions).setup('password');
|
||||
*
|
||||
* Get the mnemonic:
|
||||
* await useOptions(pebblenetOptions).recoverMnemonic(password);
|
||||
*
|
||||
* Create contract:
|
||||
* const contract = CW721(client, pebblenetOptions.fees);
|
||||
*
|
||||
* Upload contract:
|
||||
* const codeId = await contract.upload(addr);
|
||||
*
|
||||
* Instantiate contract example:
|
||||
* const initMsg = {
|
||||
* name: "Potato Coin",
|
||||
* symbol: "TATER",
|
||||
* minter: addr
|
||||
* };
|
||||
* const instance = await contract.instantiate(addr, codeId, initMsg, 'Potato Coin!');
|
||||
* If you want to use this code inside an app, you will need several imports from https://github.com/CosmWasm/cosmjs
|
||||
*/
|
||||
|
||||
interface Options {
|
||||
readonly httpUrl: string
|
||||
readonly networkId: string
|
||||
readonly feeToken: string
|
||||
readonly bech32prefix: string
|
||||
readonly hdPath: readonly Slip10RawIndex[]
|
||||
readonly faucetUrl?: string
|
||||
readonly defaultKeyFile: string,
|
||||
readonly fees: {
|
||||
upload: StdFee,
|
||||
init: StdFee,
|
||||
exec: StdFee
|
||||
}
|
||||
}
|
||||
|
||||
const pebblenetGasPrice = GasPrice.fromString("0.01upebble");
|
||||
const pebblenetOptions: Options = {
|
||||
httpUrl: 'https://rpc.pebblenet.cosmwasm.com',
|
||||
networkId: 'pebblenet-1',
|
||||
bech32prefix: 'wasm',
|
||||
feeToken: 'upebble',
|
||||
faucetUrl: 'https://faucet.pebblenet.cosmwasm.com/credit',
|
||||
hdPath: makeCosmoshubPath(0),
|
||||
defaultKeyFile: path.join(process.env.HOME, ".pebblenet.key"),
|
||||
fees: {
|
||||
upload: calculateFee(1500000, pebblenetGasPrice),
|
||||
init: calculateFee(500000, pebblenetGasPrice),
|
||||
exec: calculateFee(200000, pebblenetGasPrice),
|
||||
},
|
||||
}
|
||||
|
||||
interface Network {
|
||||
setup: (password: string, filename?: string) => Promise<[string, SigningCosmWasmClient]>
|
||||
recoverMnemonic: (password: string, filename?: string) => Promise<string>
|
||||
}
|
||||
|
||||
const useOptions = (options: Options): Network => {
|
||||
|
||||
const loadOrCreateWallet = async (options: Options, filename: string, password: string): Promise<DirectSecp256k1HdWallet> => {
|
||||
let encrypted: string;
|
||||
try {
|
||||
encrypted = fs.readFileSync(filename, 'utf8');
|
||||
} catch (err) {
|
||||
// generate if no file exists
|
||||
const wallet = await DirectSecp256k1HdWallet.generate(12, {hdPaths: [options.hdPath], prefix: options.bech32prefix});
|
||||
const encrypted = await wallet.serialize(password);
|
||||
fs.writeFileSync(filename, encrypted, 'utf8');
|
||||
return wallet;
|
||||
}
|
||||
// otherwise, decrypt the file (we cannot put deserialize inside try or it will over-write on a bad password)
|
||||
const wallet = await DirectSecp256k1HdWallet.deserialize(encrypted, password);
|
||||
return wallet;
|
||||
};
|
||||
|
||||
const connect = async (
|
||||
wallet: DirectSecp256k1HdWallet,
|
||||
options: Options
|
||||
): Promise<SigningCosmWasmClient> => {
|
||||
const clientOptions = {
|
||||
prefix: options.bech32prefix
|
||||
}
|
||||
return await SigningCosmWasmClient.connectWithSigner(options.httpUrl, wallet, clientOptions)
|
||||
};
|
||||
|
||||
const hitFaucet = async (
|
||||
faucetUrl: string,
|
||||
address: string,
|
||||
denom: string
|
||||
): Promise<void> => {
|
||||
await axios.post(faucetUrl, { denom, address });
|
||||
}
|
||||
|
||||
const setup = async (password: string, filename?: string): Promise<[string, SigningCosmWasmClient]> => {
|
||||
const keyfile = filename || options.defaultKeyFile;
|
||||
const wallet = await loadOrCreateWallet(pebblenetOptions, keyfile, password);
|
||||
const client = await connect(wallet, pebblenetOptions);
|
||||
|
||||
const [account] = await wallet.getAccounts();
|
||||
// ensure we have some tokens
|
||||
if (options.faucetUrl) {
|
||||
const tokens = await client.getBalance(account.address, options.feeToken)
|
||||
if (tokens.amount === '0') {
|
||||
console.log(`Getting ${options.feeToken} from faucet`);
|
||||
await hitFaucet(options.faucetUrl, account.address, options.feeToken);
|
||||
}
|
||||
}
|
||||
|
||||
return [account.address, client];
|
||||
}
|
||||
|
||||
const recoverMnemonic = async (password: string, filename?: string): Promise<string> => {
|
||||
const keyfile = filename || options.defaultKeyFile;
|
||||
const wallet = await loadOrCreateWallet(pebblenetOptions, keyfile, password);
|
||||
return wallet.mnemonic;
|
||||
}
|
||||
|
||||
return { setup, recoverMnemonic };
|
||||
}
|
||||
|
||||
type TokenId = string
|
||||
|
||||
interface Balances {
|
||||
readonly address: string
|
||||
readonly amount: string // decimal as string
|
||||
}
|
||||
|
||||
interface MintInfo {
|
||||
readonly minter: string
|
||||
readonly cap?: string // decimal as string
|
||||
}
|
||||
|
||||
interface ContractInfo {
|
||||
readonly name: string
|
||||
readonly symbol: string
|
||||
}
|
||||
|
||||
interface NftInfo {
|
||||
readonly name: string,
|
||||
readonly description: string,
|
||||
readonly image: any
|
||||
}
|
||||
|
||||
interface Access {
|
||||
readonly owner: string,
|
||||
readonly approvals: []
|
||||
}
|
||||
interface AllNftInfo {
|
||||
readonly access: Access,
|
||||
readonly info: NftInfo
|
||||
}
|
||||
|
||||
interface Operators {
|
||||
readonly operators: []
|
||||
}
|
||||
|
||||
interface Count {
|
||||
readonly count: number
|
||||
}
|
||||
|
||||
interface InitMsg {
|
||||
readonly name: string
|
||||
readonly symbol: string
|
||||
readonly minter: string
|
||||
}
|
||||
// Better to use this interface?
|
||||
interface MintMsg {
|
||||
readonly token_id: TokenId
|
||||
readonly owner: string
|
||||
readonly name: string
|
||||
readonly description?: string
|
||||
readonly image?: string
|
||||
}
|
||||
|
||||
type Expiration = { readonly at_height: number } | { readonly at_time: number } | { readonly never: {} };
|
||||
|
||||
interface AllowanceResponse {
|
||||
readonly allowance: string; // integer as string
|
||||
readonly expires: Expiration;
|
||||
}
|
||||
|
||||
interface AllowanceInfo {
|
||||
readonly allowance: string; // integer as string
|
||||
readonly spender: string; // bech32 address
|
||||
readonly expires: Expiration;
|
||||
}
|
||||
|
||||
interface AllAllowancesResponse {
|
||||
readonly allowances: readonly AllowanceInfo[];
|
||||
}
|
||||
|
||||
interface AllAccountsResponse {
|
||||
// list of bech32 address that have a balance
|
||||
readonly accounts: readonly string[];
|
||||
}
|
||||
|
||||
interface TokensResponse {
|
||||
readonly tokens: readonly string[];
|
||||
}
|
||||
|
||||
interface CW721Instance {
|
||||
readonly contractAddress: string
|
||||
|
||||
// queries
|
||||
allowance: (owner: string, spender: string) => Promise<AllowanceResponse>
|
||||
allAllowances: (owner: string, startAfter?: string, limit?: number) => Promise<AllAllowancesResponse>
|
||||
allAccounts: (startAfter?: string, limit?: number) => Promise<readonly string[]>
|
||||
minter: () => Promise<MintInfo>
|
||||
contractInfo: () => Promise<ContractInfo>
|
||||
nftInfo: (tokenId: TokenId) => Promise<NftInfo>
|
||||
allNftInfo: (tokenId: TokenId) => Promise<AllNftInfo>
|
||||
ownerOf: (tokenId: TokenId) => Promise<Access>
|
||||
approvedForAll: (owner: string, include_expired?: boolean, start_after?: string, limit?: number) => Promise<Operators>
|
||||
numTokens: () => Promise<Count>
|
||||
tokens: (owner: string, startAfter?: string, limit?: number) => Promise<TokensResponse>
|
||||
allTokens: (startAfter?: string, limit?: number) => Promise<TokensResponse>
|
||||
|
||||
// actions
|
||||
mint: (senderAddress: string, tokenId: TokenId, owner: string, name: string, level: number, description?: string, image?: string) => Promise<string>
|
||||
transferNft: (senderAddress: string, recipient: string, tokenId: TokenId) => Promise<string>
|
||||
sendNft: (senderAddress: string, contract: string, token_id: TokenId, msg?: BinaryType) => Promise<string>
|
||||
approve: (senderAddress: string, spender: string, tokenId: TokenId, expires?: Expiration) => Promise<string>
|
||||
approveAll: (senderAddress: string, operator: string, expires?: Expiration) => Promise<string>
|
||||
revoke: (senderAddress: string, spender: string, tokenId: TokenId) => Promise<string>
|
||||
revokeAll: (senderAddress: string, operator: string) => Promise<string>
|
||||
}
|
||||
|
||||
interface CW721Contract {
|
||||
// upload a code blob and returns a codeId
|
||||
upload: (senderAddress: string) => Promise<number>
|
||||
|
||||
// instantiates a cw721 contract
|
||||
// codeId must come from a previous deploy
|
||||
// label is the public name of the contract in listing
|
||||
// if you set admin, you can run migrations on this contract (likely client.senderAddress)
|
||||
instantiate: (senderAddress: string, codeId: number, initMsg: Record<string, unknown>, label: string, admin?: string) => Promise<CW721Instance>
|
||||
|
||||
use: (contractAddress: string) => CW721Instance
|
||||
}
|
||||
|
||||
|
||||
export const CW721 = (client: SigningCosmWasmClient, fees: Options['fees']): CW721Contract => {
|
||||
const use = (contractAddress: string): CW721Instance => {
|
||||
|
||||
const allowance = async (owner: string, spender: string): Promise<AllowanceResponse> => {
|
||||
return client.queryContractSmart(contractAddress, { allowance: { owner, spender } });
|
||||
};
|
||||
|
||||
const allAllowances = async (owner: string, startAfter?: string, limit?: number): Promise<AllAllowancesResponse> => {
|
||||
return client.queryContractSmart(contractAddress, { all_allowances: { owner, start_after: startAfter, limit } });
|
||||
};
|
||||
|
||||
const allAccounts = async (startAfter?: string, limit?: number): Promise<readonly string[]> => {
|
||||
const accounts: AllAccountsResponse = await client.queryContractSmart(contractAddress, { all_accounts: { start_after: startAfter, limit } });
|
||||
return accounts.accounts;
|
||||
};
|
||||
|
||||
const minter = async (): Promise<MintInfo> => {
|
||||
return client.queryContractSmart(contractAddress, { minter: {} });
|
||||
};
|
||||
|
||||
const contractInfo = async (): Promise<ContractInfo> => {
|
||||
return client.queryContractSmart(contractAddress, { contract_info: {} });
|
||||
};
|
||||
|
||||
const nftInfo = async (token_id: TokenId): Promise<NftInfo> => {
|
||||
return client.queryContractSmart(contractAddress, { nft_info: { token_id } });
|
||||
}
|
||||
|
||||
const allNftInfo = async (token_id: TokenId): Promise<AllNftInfo> => {
|
||||
return client.queryContractSmart(contractAddress, { all_nft_info: { token_id } });
|
||||
}
|
||||
|
||||
const ownerOf = async (token_id: TokenId): Promise<Access> => {
|
||||
return await client.queryContractSmart(contractAddress, { owner_of: { token_id } });
|
||||
}
|
||||
|
||||
const approvedForAll = async (owner: string, include_expired?: boolean, start_after?: string, limit?: number): Promise<Operators> => {
|
||||
return await client.queryContractSmart(contractAddress, { approved_for_all: { owner, include_expired, start_after, limit } })
|
||||
}
|
||||
|
||||
// total number of tokens issued
|
||||
const numTokens = async (): Promise<Count> => {
|
||||
return client.queryContractSmart(contractAddress, { num_tokens: {} });
|
||||
}
|
||||
|
||||
// list all token_ids that belong to a given owner
|
||||
const tokens = async (owner: string, start_after?: string, limit?: number): Promise<TokensResponse> => {
|
||||
return client.queryContractSmart(contractAddress, { tokens: { owner, start_after, limit } });
|
||||
}
|
||||
|
||||
const allTokens = async (start_after?: string, limit?: number): Promise<TokensResponse> => {
|
||||
return client.queryContractSmart(contractAddress, { all_tokens: { start_after, limit } });
|
||||
}
|
||||
|
||||
// actions
|
||||
const mint = async (senderAddress: string, token_id: TokenId, owner: string, name: string, level: number, description?: string, image?: string): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { mint: { token_id, owner, name, level, description, image } }, fees.exec);
|
||||
return result.transactionHash;
|
||||
}
|
||||
|
||||
// transfers ownership, returns transactionHash
|
||||
const transferNft = async (senderAddress: string, recipient: string, token_id: TokenId): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { transfer_nft: { recipient, token_id } }, fees.exec);
|
||||
return result.transactionHash;
|
||||
}
|
||||
|
||||
// sends an nft token to another contract (TODO: msg type any needs to be revisited once receiveNft is implemented)
|
||||
const sendNft = async (senderAddress: string, contract: string, token_id: TokenId, msg?: any): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { send_nft: { contract, token_id, msg } }, fees.exec)
|
||||
return result.transactionHash;
|
||||
}
|
||||
|
||||
const approve = async (senderAddress: string, spender: string, token_id: TokenId, expires?: Expiration): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { approve: { spender, token_id, expires } }, fees.exec);
|
||||
return result.transactionHash;
|
||||
}
|
||||
|
||||
const approveAll = async (senderAddress: string, operator: string, expires?: Expiration): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { approve_all: { operator, expires } }, fees.exec)
|
||||
return result.transactionHash
|
||||
}
|
||||
|
||||
const revoke = async (senderAddress: string, spender: string, token_id: TokenId): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { revoke: { spender, token_id } }, fees.exec);
|
||||
return result.transactionHash;
|
||||
}
|
||||
|
||||
const revokeAll = async (senderAddress: string, operator: string): Promise<string> => {
|
||||
const result = await client.execute(senderAddress, contractAddress, { revoke_all: { operator } }, fees.exec)
|
||||
return result.transactionHash;
|
||||
}
|
||||
|
||||
return {
|
||||
contractAddress,
|
||||
allowance,
|
||||
allAllowances,
|
||||
allAccounts,
|
||||
minter,
|
||||
contractInfo,
|
||||
nftInfo,
|
||||
allNftInfo,
|
||||
ownerOf,
|
||||
approvedForAll,
|
||||
numTokens,
|
||||
tokens,
|
||||
allTokens,
|
||||
mint,
|
||||
transferNft,
|
||||
sendNft,
|
||||
approve,
|
||||
approveAll,
|
||||
revoke,
|
||||
revokeAll
|
||||
};
|
||||
}
|
||||
|
||||
const downloadWasm = async (url: string): Promise<Uint8Array> => {
|
||||
const r = await axios.get(url, { responseType: 'arraybuffer' })
|
||||
if (r.status !== 200) {
|
||||
throw new Error(`Download error: ${r.status}`)
|
||||
}
|
||||
return r.data
|
||||
}
|
||||
|
||||
const upload = async (senderAddress: string): Promise<number> => {
|
||||
const sourceUrl = "https://github.com/CosmWasm/cosmwasm-plus/releases/download/v0.9.0/cw721_base.wasm";
|
||||
const wasm = await downloadWasm(sourceUrl);
|
||||
const result = await client.upload(senderAddress, wasm, fees.upload);
|
||||
return result.codeId;
|
||||
}
|
||||
|
||||
const instantiate = async (senderAddress: string, codeId: number, initMsg: Record<string, unknown>, label: string, admin?: string): Promise<CW721Instance> => {
|
||||
const result = await client.instantiate(senderAddress, codeId, initMsg, label, fees.init, { memo: `Init ${label}`, admin });
|
||||
return use(result.contractAddress);
|
||||
}
|
||||
|
||||
return { upload, instantiate, use };
|
||||
}
|
|
@ -1,155 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "AllNftInfoResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"access",
|
||||
"info"
|
||||
],
|
||||
"properties": {
|
||||
"access": {
|
||||
"description": "Who can transfer the token",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/OwnerOfResponse"
|
||||
}
|
||||
]
|
||||
},
|
||||
"info": {
|
||||
"description": "Data on the token itself,",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/NftInfoResponse_for_Nullable_Empty"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Empty": {
|
||||
"description": "An empty struct that serves as a placeholder in different places, such as contracts that don't set a custom message.\n\nIt is designed to be expressable in correct JSON and JSON Schema but contains no meaningful data. Previously we used enums without cases, but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451)",
|
||||
"type": "object"
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"NftInfoResponse_for_Nullable_Empty": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "You can add any custom metadata here when you extend cw721-base",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Empty"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"OwnerOfResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"description": "If set this address is approved to transfer/send the token as well",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"owner": {
|
||||
"description": "Owner of the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,94 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ApprovalResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approval"
|
||||
],
|
||||
"properties": {
|
||||
"approval": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ApprovalsResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ContractInfoResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"symbol"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"symbol": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,310 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ExecuteMsg",
|
||||
"description": "This is like Cw721ExecuteMsg but we add a Mint command for an owner to make this stand-alone. You will likely want to remove mint and use other control logic in any contract that inherits this.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Transfer is a base message to move a token to another account without triggering actions",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"transfer_nft"
|
||||
],
|
||||
"properties": {
|
||||
"transfer_nft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"recipient",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"recipient": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Send is a base message to transfer a token to a contract and trigger an action on the receiving contract.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"send_nft"
|
||||
],
|
||||
"properties": {
|
||||
"send_nft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"contract",
|
||||
"msg",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"contract": {
|
||||
"type": "string"
|
||||
},
|
||||
"msg": {
|
||||
"$ref": "#/definitions/Binary"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Allows operator to transfer / send the token from the owner's account. If expiration is set, then this allowance has a time/height limit",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approve"
|
||||
],
|
||||
"properties": {
|
||||
"approve": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Remove previously granted Approval",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"revoke"
|
||||
],
|
||||
"properties": {
|
||||
"revoke": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Allows operator to transfer / send any token from the owner's account. If expiration is set, then this allowance has a time/height limit",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approve_all"
|
||||
],
|
||||
"properties": {
|
||||
"approve_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"operator": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Remove previously granted ApproveAll permission",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"revoke_all"
|
||||
],
|
||||
"properties": {
|
||||
"revoke_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator"
|
||||
],
|
||||
"properties": {
|
||||
"operator": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Mint a new NFT, can only be called by the contract minter",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"mint"
|
||||
],
|
||||
"properties": {
|
||||
"mint": {
|
||||
"$ref": "#/definitions/MintMsg_for_Nullable_Empty"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Burn an NFT the sender has access to",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"burn"
|
||||
],
|
||||
"properties": {
|
||||
"burn": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
],
|
||||
"definitions": {
|
||||
"Binary": {
|
||||
"description": "Binary is a wrapper around Vec<u8> to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec<u8>",
|
||||
"type": "string"
|
||||
},
|
||||
"Empty": {
|
||||
"description": "An empty struct that serves as a placeholder in different places, such as contracts that don't set a custom message.\n\nIt is designed to be expressable in correct JSON and JSON Schema but contains no meaningful data. Previously we used enums without cases, but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451)",
|
||||
"type": "object"
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"MintMsg_for_Nullable_Empty": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "Any custom extension used by this contract",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Empty"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"owner": {
|
||||
"description": "The owner of the newly minter NFT",
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"description": "Unique ID of the NFT",
|
||||
"type": "string"
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "InstantiateMsg",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"minter",
|
||||
"name",
|
||||
"symbol"
|
||||
],
|
||||
"properties": {
|
||||
"minter": {
|
||||
"description": "The minter is the only one who can create new NFTs. This is designed for a base NFT that is controlled by an external program or contract. You will likely replace this with custom logic in custom NFTs",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name of the NFT contract",
|
||||
"type": "string"
|
||||
},
|
||||
"symbol": {
|
||||
"description": "Symbol of the NFT contract",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "MinterResponse",
|
||||
"description": "Shows who can mint these tokens",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"minter"
|
||||
],
|
||||
"properties": {
|
||||
"minter": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NftInfoResponse",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "You can add any custom metadata here when you extend cw721-base",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Empty"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Empty": {
|
||||
"description": "An empty struct that serves as a placeholder in different places, such as contracts that don't set a custom message.\n\nIt is designed to be expressable in correct JSON and JSON Schema but contains no meaningful data. Previously we used enums without cases, but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451)",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NumTokensResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"count"
|
||||
],
|
||||
"properties": {
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "OperatorsResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operators"
|
||||
],
|
||||
"properties": {
|
||||
"operators": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,103 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "OwnerOfResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"description": "If set this address is approved to transfer/send the token as well",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"owner": {
|
||||
"description": "Owner of the token",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,285 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "QueryMsg",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Return the owner of the given token, error if token does not exist Return type: OwnerOfResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner_of"
|
||||
],
|
||||
"properties": {
|
||||
"owner_of": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Return operator that can access all of the owner's tokens. Return type: `ApprovalResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approval"
|
||||
],
|
||||
"properties": {
|
||||
"approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Return approvals that a token has Return type: `ApprovalsResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "List all operators that can access all of the owner's tokens Return type: `OperatorsResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_operators"
|
||||
],
|
||||
"properties": {
|
||||
"all_operators": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired items, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Total number of tokens issued",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"num_tokens"
|
||||
],
|
||||
"properties": {
|
||||
"num_tokens": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns top-level metadata about the contract: `ContractInfoResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"contract_info"
|
||||
],
|
||||
"properties": {
|
||||
"contract_info": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema* but directly from the contract: `NftInfoResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"nft_info"
|
||||
],
|
||||
"properties": {
|
||||
"nft_info": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns the result of both `NftInfo` and `OwnerOf` as one query as an optimization for clients: `AllNftInfo`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_nft_info"
|
||||
],
|
||||
"properties": {
|
||||
"all_nft_info": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With Enumerable extension. Returns all tokens owned by the given address, [] if unset. Return type: TokensResponse.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"tokens"
|
||||
],
|
||||
"properties": {
|
||||
"tokens": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With Enumerable extension. Requires pagination. Lists all token_ids controlled by the contract. Return type: TokensResponse.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_tokens"
|
||||
],
|
||||
"properties": {
|
||||
"all_tokens": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"minter"
|
||||
],
|
||||
"properties": {
|
||||
"minter": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "TokensResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"tokens"
|
||||
],
|
||||
"properties": {
|
||||
"tokens": {
|
||||
"description": "Contains all token_ids in lexicographical ordering If there are more than `limit`, use `start_from` in future queries to achieve pagination.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,756 +0,0 @@
|
|||
#![cfg(test)]
|
||||
use cosmwasm_std::{
|
||||
from_binary,
|
||||
testing::{
|
||||
mock_dependencies,
|
||||
mock_env,
|
||||
mock_info,
|
||||
},
|
||||
to_binary,
|
||||
CosmosMsg,
|
||||
DepsMut,
|
||||
Empty,
|
||||
Response,
|
||||
WasmMsg,
|
||||
};
|
||||
|
||||
use cw721::{
|
||||
Approval,
|
||||
ApprovalResponse,
|
||||
ContractInfoResponse,
|
||||
Cw721Query,
|
||||
Cw721ReceiveMsg,
|
||||
Expiration,
|
||||
NftInfoResponse,
|
||||
OperatorsResponse,
|
||||
OwnerOfResponse,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
ContractError,
|
||||
Cw721Contract,
|
||||
ExecuteMsg,
|
||||
Extension,
|
||||
InstantiateMsg,
|
||||
MintMsg,
|
||||
QueryMsg,
|
||||
};
|
||||
|
||||
const MINTER: &str = "merlin";
|
||||
const CONTRACT_NAME: &str = "Magic Power";
|
||||
const SYMBOL: &str = "MGK";
|
||||
|
||||
fn setup_contract(deps: DepsMut<'_>) -> Cw721Contract<'static, Extension, Empty> {
|
||||
let contract = Cw721Contract::default();
|
||||
let msg = InstantiateMsg {
|
||||
name: CONTRACT_NAME.to_string(),
|
||||
symbol: SYMBOL.to_string(),
|
||||
minter: String::from(MINTER),
|
||||
};
|
||||
let info = mock_info("creator", &[]);
|
||||
let res = contract.instantiate(deps, mock_env(), info, msg).unwrap();
|
||||
assert_eq!(0, res.messages.len());
|
||||
contract
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proper_instantiation() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = Cw721Contract::<Extension, Empty>::default();
|
||||
|
||||
let msg = InstantiateMsg {
|
||||
name: CONTRACT_NAME.to_string(),
|
||||
symbol: SYMBOL.to_string(),
|
||||
minter: String::from(MINTER),
|
||||
};
|
||||
let info = mock_info("creator", &[]);
|
||||
|
||||
// we can just call .unwrap() to assert this was a success
|
||||
let res = contract
|
||||
.instantiate(deps.as_mut(), mock_env(), info, msg)
|
||||
.unwrap();
|
||||
assert_eq!(0, res.messages.len());
|
||||
|
||||
// it worked, let's query the state
|
||||
let res = contract.minter(deps.as_ref()).unwrap();
|
||||
assert_eq!(MINTER, res.minter);
|
||||
let info = contract.contract_info(deps.as_ref()).unwrap();
|
||||
assert_eq!(
|
||||
info,
|
||||
ContractInfoResponse {
|
||||
name: CONTRACT_NAME.to_string(),
|
||||
symbol: SYMBOL.to_string(),
|
||||
}
|
||||
);
|
||||
|
||||
let count = contract.num_tokens(deps.as_ref()).unwrap();
|
||||
assert_eq!(0, count.count);
|
||||
|
||||
// list the token_ids
|
||||
let tokens = contract.all_tokens(deps.as_ref(), None, None).unwrap();
|
||||
assert_eq!(0, tokens.tokens.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minting() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
|
||||
let token_id = "petrify".to_string();
|
||||
let token_uri = "https://www.merriam-webster.com/dictionary/petrify".to_string();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id.clone(),
|
||||
owner: String::from("medusa"),
|
||||
token_uri: Some(token_uri.clone()),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
// random cannot mint
|
||||
let random = mock_info("random", &[]);
|
||||
let err = contract
|
||||
.execute(deps.as_mut(), mock_env(), random, mint_msg.clone())
|
||||
.unwrap_err();
|
||||
assert_eq!(err, ContractError::Unauthorized {});
|
||||
|
||||
// minter can mint
|
||||
let allowed = mock_info(MINTER, &[]);
|
||||
let _ = contract
|
||||
.execute(deps.as_mut(), mock_env(), allowed, mint_msg)
|
||||
.unwrap();
|
||||
|
||||
// ensure num tokens increases
|
||||
let count = contract.num_tokens(deps.as_ref()).unwrap();
|
||||
assert_eq!(1, count.count);
|
||||
|
||||
// unknown nft returns error
|
||||
let _ = contract
|
||||
.nft_info(deps.as_ref(), "unknown".to_string())
|
||||
.unwrap_err();
|
||||
|
||||
// this nft info is correct
|
||||
let info = contract.nft_info(deps.as_ref(), token_id.clone()).unwrap();
|
||||
assert_eq!(
|
||||
info,
|
||||
NftInfoResponse::<Extension> {
|
||||
token_uri: Some(token_uri),
|
||||
extension: None,
|
||||
}
|
||||
);
|
||||
|
||||
// owner info is correct
|
||||
let owner = contract
|
||||
.owner_of(deps.as_ref(), mock_env(), token_id.clone(), true)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
owner,
|
||||
OwnerOfResponse {
|
||||
owner: String::from("medusa"),
|
||||
approvals: vec![],
|
||||
}
|
||||
);
|
||||
|
||||
// Cannot mint same token_id again
|
||||
let mint_msg2 = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id.clone(),
|
||||
owner: String::from("hercules"),
|
||||
token_uri: None,
|
||||
extension: None,
|
||||
});
|
||||
|
||||
let allowed = mock_info(MINTER, &[]);
|
||||
let err = contract
|
||||
.execute(deps.as_mut(), mock_env(), allowed, mint_msg2)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, ContractError::Claimed {});
|
||||
|
||||
// list the token_ids
|
||||
let tokens = contract.all_tokens(deps.as_ref(), None, None).unwrap();
|
||||
assert_eq!(1, tokens.tokens.len());
|
||||
assert_eq!(vec![token_id], tokens.tokens);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burning() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
|
||||
let token_id = "petrify".to_string();
|
||||
let token_uri = "https://www.merriam-webster.com/dictionary/petrify".to_string();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id.clone(),
|
||||
owner: MINTER.to_string(),
|
||||
token_uri: Some(token_uri),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
let burn_msg = ExecuteMsg::Burn { token_id };
|
||||
|
||||
// mint some NFT
|
||||
let allowed = mock_info(MINTER, &[]);
|
||||
let _ = contract
|
||||
.execute(deps.as_mut(), mock_env(), allowed.clone(), mint_msg)
|
||||
.unwrap();
|
||||
|
||||
// random not allowed to burn
|
||||
let random = mock_info("random", &[]);
|
||||
let err = contract
|
||||
.execute(deps.as_mut(), mock_env(), random, burn_msg.clone())
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(err, ContractError::Unauthorized {});
|
||||
|
||||
let _ = contract
|
||||
.execute(deps.as_mut(), mock_env(), allowed, burn_msg)
|
||||
.unwrap();
|
||||
|
||||
// ensure num tokens decreases
|
||||
let count = contract.num_tokens(deps.as_ref()).unwrap();
|
||||
assert_eq!(0, count.count);
|
||||
|
||||
// trying to get nft returns error
|
||||
let _ = contract
|
||||
.nft_info(deps.as_ref(), "petrify".to_string())
|
||||
.unwrap_err();
|
||||
|
||||
// list the token_ids
|
||||
let tokens = contract.all_tokens(deps.as_ref(), None, None).unwrap();
|
||||
assert!(tokens.tokens.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transferring_nft() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
|
||||
// Mint a token
|
||||
let token_id = "melt".to_string();
|
||||
let token_uri = "https://www.merriam-webster.com/dictionary/melt".to_string();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id.clone(),
|
||||
owner: String::from("venus"),
|
||||
token_uri: Some(token_uri),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
let minter = mock_info(MINTER, &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter, mint_msg)
|
||||
.unwrap();
|
||||
|
||||
// random cannot transfer
|
||||
let random = mock_info("random", &[]);
|
||||
let transfer_msg = ExecuteMsg::TransferNft {
|
||||
recipient: String::from("random"),
|
||||
token_id: token_id.clone(),
|
||||
};
|
||||
|
||||
let err = contract
|
||||
.execute(deps.as_mut(), mock_env(), random, transfer_msg)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, ContractError::Unauthorized {});
|
||||
|
||||
// owner can
|
||||
let random = mock_info("venus", &[]);
|
||||
let transfer_msg = ExecuteMsg::TransferNft {
|
||||
recipient: String::from("random"),
|
||||
token_id: token_id.clone(),
|
||||
};
|
||||
|
||||
let res = contract
|
||||
.execute(deps.as_mut(), mock_env(), random, transfer_msg)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
res,
|
||||
Response::new()
|
||||
.add_attribute("action", "transfer_nft")
|
||||
.add_attribute("sender", "venus")
|
||||
.add_attribute("recipient", "random")
|
||||
.add_attribute("token_id", token_id)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sending_nft() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
|
||||
// Mint a token
|
||||
let token_id = "melt".to_string();
|
||||
let token_uri = "https://www.merriam-webster.com/dictionary/melt".to_string();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id.clone(),
|
||||
owner: String::from("venus"),
|
||||
token_uri: Some(token_uri),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
let minter = mock_info(MINTER, &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter, mint_msg)
|
||||
.unwrap();
|
||||
|
||||
let msg = to_binary("You now have the melting power").unwrap();
|
||||
let target = String::from("another_contract");
|
||||
let send_msg = ExecuteMsg::SendNft {
|
||||
contract: target.clone(),
|
||||
token_id: token_id.clone(),
|
||||
msg: msg.clone(),
|
||||
};
|
||||
|
||||
let random = mock_info("random", &[]);
|
||||
let err = contract
|
||||
.execute(deps.as_mut(), mock_env(), random, send_msg.clone())
|
||||
.unwrap_err();
|
||||
assert_eq!(err, ContractError::Unauthorized {});
|
||||
|
||||
// but owner can
|
||||
let random = mock_info("venus", &[]);
|
||||
let res = contract
|
||||
.execute(deps.as_mut(), mock_env(), random, send_msg)
|
||||
.unwrap();
|
||||
|
||||
let payload = Cw721ReceiveMsg {
|
||||
sender: String::from("venus"),
|
||||
token_id: token_id.clone(),
|
||||
msg,
|
||||
};
|
||||
let expected = payload.into_cosmos_msg(target.clone()).unwrap();
|
||||
// ensure expected serializes as we think it should
|
||||
match &expected {
|
||||
CosmosMsg::Wasm(WasmMsg::Execute { contract_addr, .. }) => {
|
||||
assert_eq!(contract_addr, &target)
|
||||
}
|
||||
m => panic!("Unexpected message type: {:?}", m),
|
||||
}
|
||||
// and make sure this is the request sent by the contract
|
||||
assert_eq!(
|
||||
res,
|
||||
Response::new()
|
||||
.add_message(expected)
|
||||
.add_attribute("action", "send_nft")
|
||||
.add_attribute("sender", "venus")
|
||||
.add_attribute("recipient", "another_contract")
|
||||
.add_attribute("token_id", token_id)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approving_revoking() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
|
||||
// Mint a token
|
||||
let token_id = "grow".to_string();
|
||||
let token_uri = "https://www.merriam-webster.com/dictionary/grow".to_string();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id.clone(),
|
||||
owner: String::from("demeter"),
|
||||
token_uri: Some(token_uri),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
let minter = mock_info(MINTER, &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter, mint_msg)
|
||||
.unwrap();
|
||||
|
||||
// Give random transferring power
|
||||
let approve_msg = ExecuteMsg::Approve {
|
||||
spender: String::from("random"),
|
||||
token_id: token_id.clone(),
|
||||
expires: None,
|
||||
};
|
||||
let owner = mock_info("demeter", &[]);
|
||||
let res = contract
|
||||
.execute(deps.as_mut(), mock_env(), owner, approve_msg)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
Response::new()
|
||||
.add_attribute("action", "approve")
|
||||
.add_attribute("sender", "demeter")
|
||||
.add_attribute("spender", "random")
|
||||
.add_attribute("token_id", token_id.clone())
|
||||
);
|
||||
|
||||
// test approval query
|
||||
let res = contract
|
||||
.approval(
|
||||
deps.as_ref(),
|
||||
mock_env(),
|
||||
token_id.clone(),
|
||||
String::from("random"),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
ApprovalResponse {
|
||||
approval: Approval {
|
||||
spender: String::from("random"),
|
||||
expires: Expiration::Never {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// random can now transfer
|
||||
let random = mock_info("random", &[]);
|
||||
let transfer_msg = ExecuteMsg::TransferNft {
|
||||
recipient: String::from("person"),
|
||||
token_id: token_id.clone(),
|
||||
};
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), random, transfer_msg)
|
||||
.unwrap();
|
||||
|
||||
// Approvals are removed / cleared
|
||||
let query_msg = QueryMsg::OwnerOf {
|
||||
token_id: token_id.clone(),
|
||||
include_expired: None,
|
||||
};
|
||||
let res: OwnerOfResponse = from_binary(
|
||||
&contract
|
||||
.query(deps.as_ref(), mock_env(), query_msg.clone())
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
OwnerOfResponse {
|
||||
owner: String::from("person"),
|
||||
approvals: vec![],
|
||||
}
|
||||
);
|
||||
|
||||
// Approve, revoke, and check for empty, to test revoke
|
||||
let approve_msg = ExecuteMsg::Approve {
|
||||
spender: String::from("random"),
|
||||
token_id: token_id.clone(),
|
||||
expires: None,
|
||||
};
|
||||
let owner = mock_info("person", &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), owner.clone(), approve_msg)
|
||||
.unwrap();
|
||||
|
||||
let revoke_msg = ExecuteMsg::Revoke {
|
||||
spender: String::from("random"),
|
||||
token_id,
|
||||
};
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), owner, revoke_msg)
|
||||
.unwrap();
|
||||
|
||||
// Approvals are now removed / cleared
|
||||
let res: OwnerOfResponse = from_binary(
|
||||
&contract
|
||||
.query(deps.as_ref(), mock_env(), query_msg)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
OwnerOfResponse {
|
||||
owner: String::from("person"),
|
||||
approvals: vec![],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approving_all_revoking_all() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
|
||||
// Mint a couple tokens (from the same owner)
|
||||
let token_id1 = "grow1".to_string();
|
||||
let token_uri1 = "https://www.merriam-webster.com/dictionary/grow1".to_string();
|
||||
|
||||
let token_id2 = "grow2".to_string();
|
||||
let token_uri2 = "https://www.merriam-webster.com/dictionary/grow2".to_string();
|
||||
|
||||
let mint_msg1 = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id1.clone(),
|
||||
owner: String::from("demeter"),
|
||||
token_uri: Some(token_uri1),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
let minter = mock_info(MINTER, &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter.clone(), mint_msg1)
|
||||
.unwrap();
|
||||
|
||||
let mint_msg2 = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id2.clone(),
|
||||
owner: String::from("demeter"),
|
||||
token_uri: Some(token_uri2),
|
||||
extension: None,
|
||||
});
|
||||
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter, mint_msg2)
|
||||
.unwrap();
|
||||
|
||||
// paginate the token_ids
|
||||
let tokens = contract.all_tokens(deps.as_ref(), None, Some(1)).unwrap();
|
||||
assert_eq!(1, tokens.tokens.len());
|
||||
assert_eq!(vec![token_id1.clone()], tokens.tokens);
|
||||
let tokens = contract
|
||||
.all_tokens(deps.as_ref(), Some(token_id1.clone()), Some(3))
|
||||
.unwrap();
|
||||
assert_eq!(1, tokens.tokens.len());
|
||||
assert_eq!(vec![token_id2.clone()], tokens.tokens);
|
||||
|
||||
// demeter gives random full (operator) power over her tokens
|
||||
let approve_all_msg = ExecuteMsg::ApproveAll {
|
||||
operator: String::from("random"),
|
||||
expires: None,
|
||||
};
|
||||
let owner = mock_info("demeter", &[]);
|
||||
let res = contract
|
||||
.execute(deps.as_mut(), mock_env(), owner, approve_all_msg)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
Response::new()
|
||||
.add_attribute("action", "approve_all")
|
||||
.add_attribute("sender", "demeter")
|
||||
.add_attribute("operator", "random")
|
||||
);
|
||||
|
||||
// random can now transfer
|
||||
let random = mock_info("random", &[]);
|
||||
let transfer_msg = ExecuteMsg::TransferNft {
|
||||
recipient: String::from("person"),
|
||||
token_id: token_id1,
|
||||
};
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), random.clone(), transfer_msg)
|
||||
.unwrap();
|
||||
|
||||
// random can now send
|
||||
let inner_msg = WasmMsg::Execute {
|
||||
contract_addr: "another_contract".into(),
|
||||
msg: to_binary("You now also have the growing power").unwrap(),
|
||||
funds: vec![],
|
||||
};
|
||||
let msg: CosmosMsg = CosmosMsg::Wasm(inner_msg);
|
||||
|
||||
let send_msg = ExecuteMsg::SendNft {
|
||||
contract: String::from("another_contract"),
|
||||
token_id: token_id2,
|
||||
msg: to_binary(&msg).unwrap(),
|
||||
};
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), random, send_msg)
|
||||
.unwrap();
|
||||
|
||||
// Approve_all, revoke_all, and check for empty, to test revoke_all
|
||||
let approve_all_msg = ExecuteMsg::ApproveAll {
|
||||
operator: String::from("operator"),
|
||||
expires: None,
|
||||
};
|
||||
// person is now the owner of the tokens
|
||||
let owner = mock_info("person", &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), owner, approve_all_msg)
|
||||
.unwrap();
|
||||
|
||||
let res = contract
|
||||
.operators(
|
||||
deps.as_ref(),
|
||||
mock_env(),
|
||||
String::from("person"),
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
OperatorsResponse {
|
||||
operators: vec![cw721::Approval {
|
||||
spender: String::from("operator"),
|
||||
expires: Expiration::Never {}
|
||||
}]
|
||||
}
|
||||
);
|
||||
|
||||
// second approval
|
||||
let buddy_expires = Expiration::AtHeight(1234567);
|
||||
let approve_all_msg = ExecuteMsg::ApproveAll {
|
||||
operator: String::from("buddy"),
|
||||
expires: Some(buddy_expires),
|
||||
};
|
||||
let owner = mock_info("person", &[]);
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), owner.clone(), approve_all_msg)
|
||||
.unwrap();
|
||||
|
||||
// and paginate queries
|
||||
let res = contract
|
||||
.operators(
|
||||
deps.as_ref(),
|
||||
mock_env(),
|
||||
String::from("person"),
|
||||
true,
|
||||
None,
|
||||
Some(1),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
OperatorsResponse {
|
||||
operators: vec![cw721::Approval {
|
||||
spender: String::from("buddy"),
|
||||
expires: buddy_expires,
|
||||
}]
|
||||
}
|
||||
);
|
||||
let res = contract
|
||||
.operators(
|
||||
deps.as_ref(),
|
||||
mock_env(),
|
||||
String::from("person"),
|
||||
true,
|
||||
Some(String::from("buddy")),
|
||||
Some(2),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
OperatorsResponse {
|
||||
operators: vec![cw721::Approval {
|
||||
spender: String::from("operator"),
|
||||
expires: Expiration::Never {}
|
||||
}]
|
||||
}
|
||||
);
|
||||
|
||||
let revoke_all_msg = ExecuteMsg::RevokeAll {
|
||||
operator: String::from("operator"),
|
||||
};
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), owner, revoke_all_msg)
|
||||
.unwrap();
|
||||
|
||||
// Approvals are removed / cleared without affecting others
|
||||
let res = contract
|
||||
.operators(
|
||||
deps.as_ref(),
|
||||
mock_env(),
|
||||
String::from("person"),
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
res,
|
||||
OperatorsResponse {
|
||||
operators: vec![cw721::Approval {
|
||||
spender: String::from("buddy"),
|
||||
expires: buddy_expires,
|
||||
}]
|
||||
}
|
||||
);
|
||||
|
||||
// ensure the filter works (nothing should be here
|
||||
let mut late_env = mock_env();
|
||||
late_env.block.height = 1234568; //expired
|
||||
let res = contract
|
||||
.operators(
|
||||
deps.as_ref(),
|
||||
late_env,
|
||||
String::from("person"),
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(0, res.operators.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_tokens_by_owner() {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let contract = setup_contract(deps.as_mut());
|
||||
let minter = mock_info(MINTER, &[]);
|
||||
|
||||
// Mint a couple tokens (from the same owner)
|
||||
let token_id1 = "grow1".to_string();
|
||||
let demeter = String::from("demeter");
|
||||
let token_id2 = "grow2".to_string();
|
||||
let ceres = String::from("ceres");
|
||||
let token_id3 = "sing".to_string();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id1.clone(),
|
||||
owner: demeter.clone(),
|
||||
token_uri: None,
|
||||
extension: None,
|
||||
});
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter.clone(), mint_msg)
|
||||
.unwrap();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id2.clone(),
|
||||
owner: ceres.clone(),
|
||||
token_uri: None,
|
||||
extension: None,
|
||||
});
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter.clone(), mint_msg)
|
||||
.unwrap();
|
||||
|
||||
let mint_msg = ExecuteMsg::Mint(MintMsg::<Extension> {
|
||||
token_id: token_id3.clone(),
|
||||
owner: demeter.clone(),
|
||||
token_uri: None,
|
||||
extension: None,
|
||||
});
|
||||
contract
|
||||
.execute(deps.as_mut(), mock_env(), minter, mint_msg)
|
||||
.unwrap();
|
||||
|
||||
// get all tokens in order:
|
||||
let expected = vec![token_id1.clone(), token_id2.clone(), token_id3.clone()];
|
||||
let tokens = contract.all_tokens(deps.as_ref(), None, None).unwrap();
|
||||
assert_eq!(&expected, &tokens.tokens);
|
||||
// paginate
|
||||
let tokens = contract.all_tokens(deps.as_ref(), None, Some(2)).unwrap();
|
||||
assert_eq!(&expected[..2], &tokens.tokens[..]);
|
||||
let tokens = contract
|
||||
.all_tokens(deps.as_ref(), Some(expected[1].clone()), None)
|
||||
.unwrap();
|
||||
assert_eq!(&expected[2..], &tokens.tokens[..]);
|
||||
|
||||
// get by owner
|
||||
let by_ceres = vec![token_id2];
|
||||
let by_demeter = vec![token_id1, token_id3];
|
||||
// all tokens by owner
|
||||
let tokens = contract
|
||||
.tokens(deps.as_ref(), demeter.clone(), None, None)
|
||||
.unwrap();
|
||||
assert_eq!(&by_demeter, &tokens.tokens);
|
||||
let tokens = contract.tokens(deps.as_ref(), ceres, None, None).unwrap();
|
||||
assert_eq!(&by_ceres, &tokens.tokens);
|
||||
|
||||
// paginate for demeter
|
||||
let tokens = contract
|
||||
.tokens(deps.as_ref(), demeter.clone(), None, Some(1))
|
||||
.unwrap();
|
||||
assert_eq!(&by_demeter[..1], &tokens.tokens[..]);
|
||||
let tokens = contract
|
||||
.tokens(deps.as_ref(), demeter, Some(by_demeter[0].clone()), Some(3))
|
||||
.unwrap();
|
||||
assert_eq!(&by_demeter[1..], &tokens.tokens[..]);
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
use cosmwasm_std::StdError;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug, PartialEq)]
|
||||
pub enum ContractError {
|
||||
#[error("{0}")]
|
||||
Std(#[from] StdError),
|
||||
|
||||
#[error("Unauthorized")]
|
||||
Unauthorized {},
|
||||
|
||||
#[error("token_id already claimed")]
|
||||
Claimed {},
|
||||
|
||||
#[error("Cannot set approval that is already expired")]
|
||||
Expired {},
|
||||
|
||||
#[error("Approval not found for: {spender}")]
|
||||
ApprovalNotFound { spender: String },
|
||||
}
|
|
@ -1,397 +0,0 @@
|
|||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
|
||||
|
||||
use cw2::set_contract_version;
|
||||
use cw721::{ContractInfoResponse, CustomMsg, Cw721Execute, Cw721ReceiveMsg, Expiration};
|
||||
|
||||
use crate::error::ContractError;
|
||||
use crate::msg::{ExecuteMsg, InstantiateMsg, MintMsg};
|
||||
use crate::state::{Approval, Cw721Contract, TokenInfo};
|
||||
|
||||
// version info for migration info
|
||||
const CONTRACT_NAME: &str = "crates.io:cw721-base";
|
||||
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
impl<'a, T, C> Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
pub fn instantiate(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
_info: MessageInfo,
|
||||
msg: InstantiateMsg,
|
||||
) -> StdResult<Response<C>> {
|
||||
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
|
||||
|
||||
let info = ContractInfoResponse {
|
||||
name: msg.name,
|
||||
symbol: msg.symbol,
|
||||
};
|
||||
self.contract_info.save(deps.storage, &info)?;
|
||||
let minter = deps.api.addr_validate(&msg.minter)?;
|
||||
self.minter.save(deps.storage, &minter)?;
|
||||
Ok(Response::default())
|
||||
}
|
||||
|
||||
pub fn execute(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
msg: ExecuteMsg<T>,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
match msg {
|
||||
ExecuteMsg::Mint(msg) => self.mint(deps, env, info, msg),
|
||||
ExecuteMsg::Approve {
|
||||
spender,
|
||||
token_id,
|
||||
expires,
|
||||
} => self.approve(deps, env, info, spender, token_id, expires),
|
||||
ExecuteMsg::Revoke { spender, token_id } => {
|
||||
self.revoke(deps, env, info, spender, token_id)
|
||||
}
|
||||
ExecuteMsg::ApproveAll { operator, expires } => {
|
||||
self.approve_all(deps, env, info, operator, expires)
|
||||
}
|
||||
ExecuteMsg::RevokeAll { operator } => self.revoke_all(deps, env, info, operator),
|
||||
ExecuteMsg::TransferNft {
|
||||
recipient,
|
||||
token_id,
|
||||
} => self.transfer_nft(deps, env, info, recipient, token_id),
|
||||
ExecuteMsg::SendNft {
|
||||
contract,
|
||||
token_id,
|
||||
msg,
|
||||
} => self.send_nft(deps, env, info, contract, token_id, msg),
|
||||
ExecuteMsg::Burn { token_id } => self.burn(deps, env, info, token_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO pull this into some sort of trait extension??
|
||||
impl<'a, T, C> Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
pub fn mint(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
info: MessageInfo,
|
||||
msg: MintMsg<T>,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
let minter = self.minter.load(deps.storage)?;
|
||||
|
||||
if info.sender != minter {
|
||||
return Err(ContractError::Unauthorized {});
|
||||
}
|
||||
|
||||
// create the token
|
||||
let token = TokenInfo {
|
||||
owner: deps.api.addr_validate(&msg.owner)?,
|
||||
approvals: vec![],
|
||||
token_uri: msg.token_uri,
|
||||
extension: msg.extension,
|
||||
};
|
||||
self.tokens
|
||||
.update(deps.storage, &msg.token_id, |old| match old {
|
||||
Some(_) => Err(ContractError::Claimed {}),
|
||||
None => Ok(token),
|
||||
})?;
|
||||
|
||||
self.increment_tokens(deps.storage)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "mint")
|
||||
.add_attribute("minter", info.sender)
|
||||
.add_attribute("token_id", msg.token_id))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, C> Cw721Execute<T, C> for Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
type Err = ContractError;
|
||||
|
||||
fn transfer_nft(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
recipient: String,
|
||||
token_id: String,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
self._transfer_nft(deps, &env, &info, &recipient, &token_id)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "transfer_nft")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("recipient", recipient)
|
||||
.add_attribute("token_id", token_id))
|
||||
}
|
||||
|
||||
fn send_nft(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
contract: String,
|
||||
token_id: String,
|
||||
msg: Binary,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
// Transfer token
|
||||
self._transfer_nft(deps, &env, &info, &contract, &token_id)?;
|
||||
|
||||
let send = Cw721ReceiveMsg {
|
||||
sender: info.sender.to_string(),
|
||||
token_id: token_id.clone(),
|
||||
msg,
|
||||
};
|
||||
|
||||
// Send message
|
||||
Ok(Response::new()
|
||||
.add_message(send.into_cosmos_msg(contract.clone())?)
|
||||
.add_attribute("action", "send_nft")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("recipient", contract)
|
||||
.add_attribute("token_id", token_id))
|
||||
}
|
||||
|
||||
fn approve(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
spender: String,
|
||||
token_id: String,
|
||||
expires: Option<Expiration>,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
self._update_approvals(deps, &env, &info, &spender, &token_id, true, expires)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "approve")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("spender", spender)
|
||||
.add_attribute("token_id", token_id))
|
||||
}
|
||||
|
||||
fn revoke(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
spender: String,
|
||||
token_id: String,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
self._update_approvals(deps, &env, &info, &spender, &token_id, false, None)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "revoke")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("spender", spender)
|
||||
.add_attribute("token_id", token_id))
|
||||
}
|
||||
|
||||
fn approve_all(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
operator: String,
|
||||
expires: Option<Expiration>,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
// reject expired data as invalid
|
||||
let expires = expires.unwrap_or_default();
|
||||
if expires.is_expired(&env.block) {
|
||||
return Err(ContractError::Expired {});
|
||||
}
|
||||
|
||||
// set the operator for us
|
||||
let operator_addr = deps.api.addr_validate(&operator)?;
|
||||
self.operators
|
||||
.save(deps.storage, (&info.sender, &operator_addr), &expires)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "approve_all")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("operator", operator))
|
||||
}
|
||||
|
||||
fn revoke_all(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
info: MessageInfo,
|
||||
operator: String,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
let operator_addr = deps.api.addr_validate(&operator)?;
|
||||
self.operators
|
||||
.remove(deps.storage, (&info.sender, &operator_addr));
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "revoke_all")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("operator", operator))
|
||||
}
|
||||
|
||||
fn burn(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
token_id: String,
|
||||
) -> Result<Response<C>, ContractError> {
|
||||
let token = self.tokens.load(deps.storage, &token_id)?;
|
||||
self.check_can_send(deps.as_ref(), &env, &info, &token)?;
|
||||
|
||||
self.tokens.remove(deps.storage, &token_id)?;
|
||||
self.decrement_tokens(deps.storage)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "burn")
|
||||
.add_attribute("sender", info.sender)
|
||||
.add_attribute("token_id", token_id))
|
||||
}
|
||||
}
|
||||
|
||||
// helpers
|
||||
impl<'a, T, C> Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
pub fn _transfer_nft(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: &Env,
|
||||
info: &MessageInfo,
|
||||
recipient: &str,
|
||||
token_id: &str,
|
||||
) -> Result<TokenInfo<T>, ContractError> {
|
||||
let mut token = self.tokens.load(deps.storage, token_id)?;
|
||||
// ensure we have permissions
|
||||
self.check_can_send(deps.as_ref(), env, info, &token)?;
|
||||
// set owner and remove existing approvals
|
||||
token.owner = deps.api.addr_validate(recipient)?;
|
||||
token.approvals = vec![];
|
||||
self.tokens.save(deps.storage, token_id, &token)?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn _update_approvals(
|
||||
&self,
|
||||
deps: DepsMut,
|
||||
env: &Env,
|
||||
info: &MessageInfo,
|
||||
spender: &str,
|
||||
token_id: &str,
|
||||
// if add == false, remove. if add == true, remove then set with this expiration
|
||||
add: bool,
|
||||
expires: Option<Expiration>,
|
||||
) -> Result<TokenInfo<T>, ContractError> {
|
||||
let mut token = self.tokens.load(deps.storage, token_id)?;
|
||||
// ensure we have permissions
|
||||
self.check_can_approve(deps.as_ref(), env, info, &token)?;
|
||||
|
||||
// update the approval list (remove any for the same spender before adding)
|
||||
let spender_addr = deps.api.addr_validate(spender)?;
|
||||
token.approvals = token
|
||||
.approvals
|
||||
.into_iter()
|
||||
.filter(|apr| apr.spender != spender_addr)
|
||||
.collect();
|
||||
|
||||
// only difference between approve and revoke
|
||||
if add {
|
||||
// reject expired data as invalid
|
||||
let expires = expires.unwrap_or_default();
|
||||
if expires.is_expired(&env.block) {
|
||||
return Err(ContractError::Expired {});
|
||||
}
|
||||
let approval = Approval {
|
||||
spender: spender_addr,
|
||||
expires,
|
||||
};
|
||||
token.approvals.push(approval);
|
||||
}
|
||||
|
||||
self.tokens.save(deps.storage, token_id, &token)?;
|
||||
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// returns true iff the sender can execute approve or reject on the contract
|
||||
pub fn check_can_approve(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: &Env,
|
||||
info: &MessageInfo,
|
||||
token: &TokenInfo<T>,
|
||||
) -> Result<(), ContractError> {
|
||||
// owner can approve
|
||||
if token.owner == info.sender {
|
||||
return Ok(());
|
||||
}
|
||||
// operator can approve
|
||||
let op = self
|
||||
.operators
|
||||
.may_load(deps.storage, (&token.owner, &info.sender))?;
|
||||
match op {
|
||||
Some(ex) => {
|
||||
if ex.is_expired(&env.block) {
|
||||
Err(ContractError::Unauthorized {})
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
None => Err(ContractError::Unauthorized {}),
|
||||
}
|
||||
}
|
||||
|
||||
/// returns true iff the sender can transfer ownership of the token
|
||||
pub fn check_can_send(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: &Env,
|
||||
info: &MessageInfo,
|
||||
token: &TokenInfo<T>,
|
||||
) -> Result<(), ContractError> {
|
||||
// owner can send
|
||||
if token.owner == info.sender {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// any non-expired token approval can send
|
||||
if token
|
||||
.approvals
|
||||
.iter()
|
||||
.any(|apr| apr.spender == info.sender && !apr.is_expired(&env.block))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// operator can send
|
||||
let op = self
|
||||
.operators
|
||||
.may_load(deps.storage, (&token.owner, &info.sender))?;
|
||||
match op {
|
||||
Some(ex) => {
|
||||
if ex.is_expired(&env.block) {
|
||||
Err(ContractError::Unauthorized {})
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
None => Err(ContractError::Unauthorized {}),
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,179 +0,0 @@
|
|||
use crate::{ExecuteMsg, QueryMsg};
|
||||
use cosmwasm_std::{to_binary, Addr, CosmosMsg, QuerierWrapper, StdResult, WasmMsg, WasmQuery};
|
||||
use cw721::{
|
||||
AllNftInfoResponse, Approval, ApprovalResponse, ApprovalsResponse, ContractInfoResponse,
|
||||
NftInfoResponse, NumTokensResponse, OperatorsResponse, OwnerOfResponse, TokensResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct Cw721Contract(pub Addr);
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Cw721Contract {
|
||||
pub fn addr(&self) -> Addr {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
pub fn call<T: Serialize>(&self, msg: ExecuteMsg<T>) -> StdResult<CosmosMsg> {
|
||||
let msg = to_binary(&msg)?;
|
||||
Ok(WasmMsg::Execute {
|
||||
contract_addr: self.addr().into(),
|
||||
msg,
|
||||
funds: vec![],
|
||||
}
|
||||
.into())
|
||||
}
|
||||
|
||||
pub fn query<T: DeserializeOwned>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
req: QueryMsg,
|
||||
) -> StdResult<T> {
|
||||
let query = WasmQuery::Smart {
|
||||
contract_addr: self.addr().into(),
|
||||
msg: to_binary(&req)?,
|
||||
}
|
||||
.into();
|
||||
querier.query(&query)
|
||||
}
|
||||
|
||||
/*** queries ***/
|
||||
|
||||
pub fn owner_of<T: Into<String>>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
token_id: T,
|
||||
include_expired: bool,
|
||||
) -> StdResult<OwnerOfResponse> {
|
||||
let req = QueryMsg::OwnerOf {
|
||||
token_id: token_id.into(),
|
||||
include_expired: Some(include_expired),
|
||||
};
|
||||
self.query(querier, req)
|
||||
}
|
||||
|
||||
pub fn approval<T: Into<String>>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
token_id: T,
|
||||
spender: T,
|
||||
include_expired: Option<bool>,
|
||||
) -> StdResult<ApprovalResponse> {
|
||||
let req = QueryMsg::Approval {
|
||||
token_id: token_id.into(),
|
||||
spender: spender.into(),
|
||||
include_expired,
|
||||
};
|
||||
let res: ApprovalResponse = self.query(querier, req)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn approvals<T: Into<String>>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
token_id: T,
|
||||
include_expired: Option<bool>,
|
||||
) -> StdResult<ApprovalsResponse> {
|
||||
let req = QueryMsg::Approvals {
|
||||
token_id: token_id.into(),
|
||||
include_expired,
|
||||
};
|
||||
let res: ApprovalsResponse = self.query(querier, req)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn all_operators<T: Into<String>>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
owner: T,
|
||||
include_expired: bool,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> StdResult<Vec<Approval>> {
|
||||
let req = QueryMsg::AllOperators {
|
||||
owner: owner.into(),
|
||||
include_expired: Some(include_expired),
|
||||
start_after,
|
||||
limit,
|
||||
};
|
||||
let res: OperatorsResponse = self.query(querier, req)?;
|
||||
Ok(res.operators)
|
||||
}
|
||||
|
||||
pub fn num_tokens(&self, querier: &QuerierWrapper) -> StdResult<u64> {
|
||||
let req = QueryMsg::NumTokens {};
|
||||
let res: NumTokensResponse = self.query(querier, req)?;
|
||||
Ok(res.count)
|
||||
}
|
||||
|
||||
/// With metadata extension
|
||||
pub fn contract_info(&self, querier: &QuerierWrapper) -> StdResult<ContractInfoResponse> {
|
||||
let req = QueryMsg::ContractInfo {};
|
||||
self.query(querier, req)
|
||||
}
|
||||
|
||||
/// With metadata extension
|
||||
pub fn nft_info<T: Into<String>, U: DeserializeOwned>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
token_id: T,
|
||||
) -> StdResult<NftInfoResponse<U>> {
|
||||
let req = QueryMsg::NftInfo {
|
||||
token_id: token_id.into(),
|
||||
};
|
||||
self.query(querier, req)
|
||||
}
|
||||
|
||||
/// With metadata extension
|
||||
pub fn all_nft_info<T: Into<String>, U: DeserializeOwned>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
token_id: T,
|
||||
include_expired: bool,
|
||||
) -> StdResult<AllNftInfoResponse<U>> {
|
||||
let req = QueryMsg::AllNftInfo {
|
||||
token_id: token_id.into(),
|
||||
include_expired: Some(include_expired),
|
||||
};
|
||||
self.query(querier, req)
|
||||
}
|
||||
|
||||
/// With enumerable extension
|
||||
pub fn tokens<T: Into<String>>(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
owner: T,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> StdResult<TokensResponse> {
|
||||
let req = QueryMsg::Tokens {
|
||||
owner: owner.into(),
|
||||
start_after,
|
||||
limit,
|
||||
};
|
||||
self.query(querier, req)
|
||||
}
|
||||
|
||||
/// With enumerable extension
|
||||
pub fn all_tokens(
|
||||
&self,
|
||||
querier: &QuerierWrapper,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> StdResult<TokensResponse> {
|
||||
let req = QueryMsg::AllTokens { start_after, limit };
|
||||
self.query(querier, req)
|
||||
}
|
||||
|
||||
/// returns true if the contract supports the metadata extension
|
||||
pub fn has_metadata(&self, querier: &QuerierWrapper) -> bool {
|
||||
self.contract_info(querier).is_ok()
|
||||
}
|
||||
|
||||
/// returns true if the contract supports the enumerable extension
|
||||
pub fn has_enumerable(&self, querier: &QuerierWrapper) -> bool {
|
||||
self.tokens(querier, self.addr(), None, Some(1)).is_ok()
|
||||
}
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
mod contract_tests;
|
||||
mod error;
|
||||
mod execute;
|
||||
pub mod helpers;
|
||||
pub mod msg;
|
||||
mod query;
|
||||
pub mod state;
|
||||
|
||||
pub use crate::error::ContractError;
|
||||
pub use crate::msg::{ExecuteMsg, InstantiateMsg, MintMsg, MinterResponse, QueryMsg};
|
||||
pub use crate::state::Cw721Contract;
|
||||
use cosmwasm_std::Empty;
|
||||
|
||||
pub type Extension = Option<Empty>;
|
||||
|
||||
#[cfg(not(feature = "library"))]
|
||||
pub mod entry {
|
||||
use super::*;
|
||||
|
||||
use cosmwasm_std::entry_point;
|
||||
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
|
||||
|
||||
// This makes a conscious choice on the various generics used by the contract
|
||||
#[entry_point]
|
||||
pub fn instantiate(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
msg: InstantiateMsg,
|
||||
) -> StdResult<Response> {
|
||||
let tract = Cw721Contract::<Extension, Empty>::default();
|
||||
tract.instantiate(deps, env, info, msg)
|
||||
}
|
||||
|
||||
#[entry_point]
|
||||
pub fn execute(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
msg: ExecuteMsg<Extension>,
|
||||
) -> Result<Response, ContractError> {
|
||||
let tract = Cw721Contract::<Extension, Empty>::default();
|
||||
tract.execute(deps, env, info, msg)
|
||||
}
|
||||
|
||||
#[entry_point]
|
||||
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
|
||||
let tract = Cw721Contract::<Extension, Empty>::default();
|
||||
tract.query(deps, env, msg)
|
||||
}
|
||||
}
|
|
@ -1,154 +0,0 @@
|
|||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use cosmwasm_std::Binary;
|
||||
use cw721::Expiration;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct InstantiateMsg {
|
||||
/// Name of the NFT contract
|
||||
pub name: String,
|
||||
/// Symbol of the NFT contract
|
||||
pub symbol: String,
|
||||
|
||||
/// The minter is the only one who can create new NFTs.
|
||||
/// This is designed for a base NFT that is controlled by an external program
|
||||
/// or contract. You will likely replace this with custom logic in custom NFTs
|
||||
pub minter: String,
|
||||
}
|
||||
|
||||
/// This is like Cw721ExecuteMsg but we add a Mint command for an owner
|
||||
/// to make this stand-alone. You will likely want to remove mint and
|
||||
/// use other control logic in any contract that inherits this.
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ExecuteMsg<T> {
|
||||
/// Transfer is a base message to move a token to another account without triggering actions
|
||||
TransferNft { recipient: String, token_id: String },
|
||||
/// Send is a base message to transfer a token to a contract and trigger an action
|
||||
/// on the receiving contract.
|
||||
SendNft {
|
||||
contract: String,
|
||||
token_id: String,
|
||||
msg: Binary,
|
||||
},
|
||||
/// Allows operator to transfer / send the token from the owner's account.
|
||||
/// If expiration is set, then this allowance has a time/height limit
|
||||
Approve {
|
||||
spender: String,
|
||||
token_id: String,
|
||||
expires: Option<Expiration>,
|
||||
},
|
||||
/// Remove previously granted Approval
|
||||
Revoke { spender: String, token_id: String },
|
||||
/// Allows operator to transfer / send any token from the owner's account.
|
||||
/// If expiration is set, then this allowance has a time/height limit
|
||||
ApproveAll {
|
||||
operator: String,
|
||||
expires: Option<Expiration>,
|
||||
},
|
||||
/// Remove previously granted ApproveAll permission
|
||||
RevokeAll { operator: String },
|
||||
|
||||
/// Mint a new NFT, can only be called by the contract minter
|
||||
Mint(MintMsg<T>),
|
||||
|
||||
/// Burn an NFT the sender has access to
|
||||
Burn { token_id: String },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct MintMsg<T> {
|
||||
/// Unique ID of the NFT
|
||||
pub token_id: String,
|
||||
/// The owner of the newly minter NFT
|
||||
pub owner: String,
|
||||
/// Universal resource identifier for this NFT
|
||||
/// Should point to a JSON file that conforms to the ERC721
|
||||
/// Metadata JSON Schema
|
||||
pub token_uri: Option<String>,
|
||||
/// Any custom extension used by this contract
|
||||
pub extension: T,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum QueryMsg {
|
||||
/// Return the owner of the given token, error if token does not exist
|
||||
/// Return type: OwnerOfResponse
|
||||
OwnerOf {
|
||||
token_id: String,
|
||||
/// unset or false will filter out expired approvals, you must set to true to see them
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// Return operator that can access all of the owner's tokens.
|
||||
/// Return type: `ApprovalResponse`
|
||||
Approval {
|
||||
token_id: String,
|
||||
spender: String,
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// Return approvals that a token has
|
||||
/// Return type: `ApprovalsResponse`
|
||||
Approvals {
|
||||
token_id: String,
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// List all operators that can access all of the owner's tokens
|
||||
/// Return type: `OperatorsResponse`
|
||||
AllOperators {
|
||||
owner: String,
|
||||
/// unset or false will filter out expired items, you must set to true to see them
|
||||
include_expired: Option<bool>,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
},
|
||||
/// Total number of tokens issued
|
||||
NumTokens {},
|
||||
|
||||
/// With MetaData Extension.
|
||||
/// Returns top-level metadata about the contract: `ContractInfoResponse`
|
||||
ContractInfo {},
|
||||
/// With MetaData Extension.
|
||||
/// Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema*
|
||||
/// but directly from the contract: `NftInfoResponse`
|
||||
NftInfo {
|
||||
token_id: String,
|
||||
},
|
||||
/// With MetaData Extension.
|
||||
/// Returns the result of both `NftInfo` and `OwnerOf` as one query as an optimization
|
||||
/// for clients: `AllNftInfo`
|
||||
AllNftInfo {
|
||||
token_id: String,
|
||||
/// unset or false will filter out expired approvals, you must set to true to see them
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// With Enumerable extension.
|
||||
/// Returns all tokens owned by the given address, [] if unset.
|
||||
/// Return type: TokensResponse.
|
||||
Tokens {
|
||||
owner: String,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
},
|
||||
/// With Enumerable extension.
|
||||
/// Requires pagination. Lists all token_ids controlled by the contract.
|
||||
/// Return type: TokensResponse.
|
||||
AllTokens {
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
},
|
||||
|
||||
// Return the minter
|
||||
Minter {},
|
||||
}
|
||||
|
||||
/// Shows who can mint these tokens
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
|
||||
pub struct MinterResponse {
|
||||
pub minter: String,
|
||||
}
|
|
@ -1,299 +0,0 @@
|
|||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use cosmwasm_std::{to_binary, Binary, BlockInfo, Deps, Env, Order, StdError, StdResult};
|
||||
|
||||
use cw0::maybe_addr;
|
||||
use cw721::{
|
||||
AllNftInfoResponse, ApprovalResponse, ApprovalsResponse, ContractInfoResponse, CustomMsg,
|
||||
Cw721Query, Expiration, NftInfoResponse, NumTokensResponse, OperatorsResponse, OwnerOfResponse,
|
||||
TokensResponse,
|
||||
};
|
||||
use cw_storage_plus::Bound;
|
||||
|
||||
use crate::msg::{MinterResponse, QueryMsg};
|
||||
use crate::state::{Approval, Cw721Contract, TokenInfo};
|
||||
|
||||
const DEFAULT_LIMIT: u32 = 10;
|
||||
const MAX_LIMIT: u32 = 30;
|
||||
|
||||
impl<'a, T, C> Cw721Query<T> for Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
fn contract_info(&self, deps: Deps) -> StdResult<ContractInfoResponse> {
|
||||
self.contract_info.load(deps.storage)
|
||||
}
|
||||
|
||||
fn num_tokens(&self, deps: Deps) -> StdResult<NumTokensResponse> {
|
||||
let count = self.token_count(deps.storage)?;
|
||||
Ok(NumTokensResponse { count })
|
||||
}
|
||||
|
||||
fn nft_info(&self, deps: Deps, token_id: String) -> StdResult<NftInfoResponse<T>> {
|
||||
let info = self.tokens.load(deps.storage, &token_id)?;
|
||||
Ok(NftInfoResponse {
|
||||
token_uri: info.token_uri,
|
||||
extension: info.extension,
|
||||
})
|
||||
}
|
||||
|
||||
fn owner_of(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: Env,
|
||||
token_id: String,
|
||||
include_expired: bool,
|
||||
) -> StdResult<OwnerOfResponse> {
|
||||
let info = self.tokens.load(deps.storage, &token_id)?;
|
||||
Ok(OwnerOfResponse {
|
||||
owner: info.owner.to_string(),
|
||||
approvals: humanize_approvals(&env.block, &info, include_expired),
|
||||
})
|
||||
}
|
||||
|
||||
/// operators returns all operators owner given access to
|
||||
fn operators(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: Env,
|
||||
owner: String,
|
||||
include_expired: bool,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> StdResult<OperatorsResponse> {
|
||||
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
|
||||
let start_addr = maybe_addr(deps.api, start_after)?;
|
||||
let start = start_addr.map(|addr| Bound::exclusive(addr.as_ref()));
|
||||
|
||||
let owner_addr = deps.api.addr_validate(&owner)?;
|
||||
let res: StdResult<Vec<_>> = self
|
||||
.operators
|
||||
.prefix(&owner_addr)
|
||||
.range(deps.storage, start, None, Order::Ascending)
|
||||
.filter(|r| {
|
||||
include_expired || r.is_err() || !r.as_ref().unwrap().1.is_expired(&env.block)
|
||||
})
|
||||
.take(limit)
|
||||
.map(parse_approval)
|
||||
.collect();
|
||||
Ok(OperatorsResponse { operators: res? })
|
||||
}
|
||||
|
||||
fn approval(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: Env,
|
||||
token_id: String,
|
||||
spender: String,
|
||||
include_expired: bool,
|
||||
) -> StdResult<ApprovalResponse> {
|
||||
let token = self.tokens.load(deps.storage, &token_id)?;
|
||||
let filtered: Vec<_> = token
|
||||
.approvals
|
||||
.into_iter()
|
||||
.filter(|t| t.spender == spender)
|
||||
.filter(|t| include_expired || !t.is_expired(&env.block))
|
||||
.map(|a| cw721::Approval {
|
||||
spender: a.spender.into_string(),
|
||||
expires: a.expires,
|
||||
})
|
||||
.collect();
|
||||
|
||||
if filtered.is_empty() {
|
||||
return Err(StdError::not_found("Approval not found"));
|
||||
}
|
||||
// we expect only one item
|
||||
let approval = filtered[0].clone();
|
||||
|
||||
Ok(ApprovalResponse { approval })
|
||||
}
|
||||
|
||||
/// approvals returns all approvals owner given access to
|
||||
fn approvals(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: Env,
|
||||
token_id: String,
|
||||
include_expired: bool,
|
||||
) -> StdResult<ApprovalsResponse> {
|
||||
let token = self.tokens.load(deps.storage, &token_id)?;
|
||||
let approvals: Vec<_> = token
|
||||
.approvals
|
||||
.into_iter()
|
||||
.filter(|t| include_expired || !t.is_expired(&env.block))
|
||||
.map(|a| cw721::Approval {
|
||||
spender: a.spender.into_string(),
|
||||
expires: a.expires,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ApprovalsResponse { approvals })
|
||||
}
|
||||
|
||||
fn tokens(
|
||||
&self,
|
||||
deps: Deps,
|
||||
owner: String,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> StdResult<TokensResponse> {
|
||||
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
|
||||
let start = start_after.map(Bound::exclusive);
|
||||
|
||||
let owner_addr = deps.api.addr_validate(&owner)?;
|
||||
let pks: Vec<_> = self
|
||||
.tokens
|
||||
.idx
|
||||
.owner
|
||||
.prefix(owner_addr)
|
||||
.keys(deps.storage, start, None, Order::Ascending)
|
||||
.take(limit)
|
||||
.collect();
|
||||
|
||||
let res: Result<Vec<_>, _> = pks.iter().map(|v| String::from_utf8(v.to_vec())).collect();
|
||||
let tokens = res.map_err(StdError::invalid_utf8)?;
|
||||
Ok(TokensResponse { tokens })
|
||||
}
|
||||
|
||||
fn all_tokens(
|
||||
&self,
|
||||
deps: Deps,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> StdResult<TokensResponse> {
|
||||
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
|
||||
let start = start_after.map(Bound::exclusive);
|
||||
|
||||
let tokens: StdResult<Vec<String>> = self
|
||||
.tokens
|
||||
.range(deps.storage, start, None, Order::Ascending)
|
||||
.take(limit)
|
||||
.map(|item| item.map(|(k, _)| String::from_utf8_lossy(&k).to_string()))
|
||||
.collect();
|
||||
Ok(TokensResponse { tokens: tokens? })
|
||||
}
|
||||
|
||||
fn all_nft_info(
|
||||
&self,
|
||||
deps: Deps,
|
||||
env: Env,
|
||||
token_id: String,
|
||||
include_expired: bool,
|
||||
) -> StdResult<AllNftInfoResponse<T>> {
|
||||
let info = self.tokens.load(deps.storage, &token_id)?;
|
||||
Ok(AllNftInfoResponse {
|
||||
access: OwnerOfResponse {
|
||||
owner: info.owner.to_string(),
|
||||
approvals: humanize_approvals(&env.block, &info, include_expired),
|
||||
},
|
||||
info: NftInfoResponse {
|
||||
token_uri: info.token_uri,
|
||||
extension: info.extension,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, C> Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
pub fn minter(&self, deps: Deps) -> StdResult<MinterResponse> {
|
||||
let minter_addr = self.minter.load(deps.storage)?;
|
||||
Ok(MinterResponse {
|
||||
minter: minter_addr.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn query(&self, deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
|
||||
match msg {
|
||||
QueryMsg::Minter {} => to_binary(&self.minter(deps)?),
|
||||
QueryMsg::ContractInfo {} => to_binary(&self.contract_info(deps)?),
|
||||
QueryMsg::NftInfo { token_id } => to_binary(&self.nft_info(deps, token_id)?),
|
||||
QueryMsg::OwnerOf {
|
||||
token_id,
|
||||
include_expired,
|
||||
} => {
|
||||
to_binary(&self.owner_of(deps, env, token_id, include_expired.unwrap_or(false))?)
|
||||
}
|
||||
QueryMsg::AllNftInfo {
|
||||
token_id,
|
||||
include_expired,
|
||||
} => to_binary(&self.all_nft_info(
|
||||
deps,
|
||||
env,
|
||||
token_id,
|
||||
include_expired.unwrap_or(false),
|
||||
)?),
|
||||
QueryMsg::AllOperators {
|
||||
owner,
|
||||
include_expired,
|
||||
start_after,
|
||||
limit,
|
||||
} => to_binary(&self.operators(
|
||||
deps,
|
||||
env,
|
||||
owner,
|
||||
include_expired.unwrap_or(false),
|
||||
start_after,
|
||||
limit,
|
||||
)?),
|
||||
QueryMsg::NumTokens {} => to_binary(&self.num_tokens(deps)?),
|
||||
QueryMsg::Tokens {
|
||||
owner,
|
||||
start_after,
|
||||
limit,
|
||||
} => to_binary(&self.tokens(deps, owner, start_after, limit)?),
|
||||
QueryMsg::AllTokens { start_after, limit } => {
|
||||
to_binary(&self.all_tokens(deps, start_after, limit)?)
|
||||
}
|
||||
QueryMsg::Approval {
|
||||
token_id,
|
||||
spender,
|
||||
include_expired,
|
||||
} => to_binary(&self.approval(
|
||||
deps,
|
||||
env,
|
||||
token_id,
|
||||
spender,
|
||||
include_expired.unwrap_or(false),
|
||||
)?),
|
||||
QueryMsg::Approvals {
|
||||
token_id,
|
||||
include_expired,
|
||||
} => {
|
||||
to_binary(&self.approvals(deps, env, token_id, include_expired.unwrap_or(false))?)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Record<V = Vec<u8>> = (Vec<u8>, V);
|
||||
fn parse_approval(item: StdResult<Record<Expiration>>) -> StdResult<cw721::Approval> {
|
||||
item.and_then(|(k, expires)| {
|
||||
let spender = String::from_utf8(k)?;
|
||||
Ok(cw721::Approval { spender, expires })
|
||||
})
|
||||
}
|
||||
|
||||
fn humanize_approvals<T>(
|
||||
block: &BlockInfo,
|
||||
info: &TokenInfo<T>,
|
||||
include_expired: bool,
|
||||
) -> Vec<cw721::Approval> {
|
||||
info.approvals
|
||||
.iter()
|
||||
.filter(|apr| include_expired || !apr.is_expired(block))
|
||||
.map(humanize_approval)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn humanize_approval(approval: &Approval) -> cw721::Approval {
|
||||
cw721::Approval {
|
||||
spender: approval.spender.to_string(),
|
||||
expires: approval.expires,
|
||||
}
|
||||
}
|
|
@ -1,141 +0,0 @@
|
|||
use schemars::JsonSchema;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use cosmwasm_std::{Addr, BlockInfo, StdResult, Storage};
|
||||
|
||||
use cw721::{ContractInfoResponse, CustomMsg, Cw721, Expiration};
|
||||
use cw_storage_plus::{Index, IndexList, IndexedMap, Item, Map, MultiIndex};
|
||||
|
||||
pub struct Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
{
|
||||
pub contract_info: Item<'a, ContractInfoResponse>,
|
||||
pub minter: Item<'a, Addr>,
|
||||
pub token_count: Item<'a, u64>,
|
||||
/// Stored as (granter, operator) giving operator full control over granter's account
|
||||
pub operators: Map<'a, (&'a Addr, &'a Addr), Expiration>,
|
||||
pub tokens: IndexedMap<'a, &'a str, TokenInfo<T>, TokenIndexes<'a, T>>,
|
||||
|
||||
pub(crate) _custom_response: PhantomData<C>,
|
||||
}
|
||||
|
||||
// This is a signal, the implementations are in other files
|
||||
impl<'a, T, C> Cw721<T, C> for Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
C: CustomMsg,
|
||||
{
|
||||
}
|
||||
|
||||
impl<T, C> Default for Cw721Contract<'static, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new(
|
||||
"nft_info",
|
||||
"minter",
|
||||
"num_tokens",
|
||||
"operators",
|
||||
"tokens",
|
||||
"tokens__owner",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, C> Cw721Contract<'a, T, C>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
{
|
||||
fn new(
|
||||
contract_key: &'a str,
|
||||
minter_key: &'a str,
|
||||
token_count_key: &'a str,
|
||||
operator_key: &'a str,
|
||||
tokens_key: &'a str,
|
||||
tokens_owner_key: &'a str,
|
||||
) -> Self {
|
||||
let indexes = TokenIndexes {
|
||||
owner: MultiIndex::new(token_owner_idx, tokens_key, tokens_owner_key),
|
||||
};
|
||||
Self {
|
||||
contract_info: Item::new(contract_key),
|
||||
minter: Item::new(minter_key),
|
||||
token_count: Item::new(token_count_key),
|
||||
operators: Map::new(operator_key),
|
||||
tokens: IndexedMap::new(tokens_key, indexes),
|
||||
_custom_response: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn token_count(&self, storage: &dyn Storage) -> StdResult<u64> {
|
||||
Ok(self.token_count.may_load(storage)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn increment_tokens(&self, storage: &mut dyn Storage) -> StdResult<u64> {
|
||||
let val = self.token_count(storage)? + 1;
|
||||
self.token_count.save(storage, &val)?;
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
pub fn decrement_tokens(&self, storage: &mut dyn Storage) -> StdResult<u64> {
|
||||
let val = self.token_count(storage)? - 1;
|
||||
self.token_count.save(storage, &val)?;
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct TokenInfo<T> {
|
||||
/// The owner of the newly minted NFT
|
||||
pub owner: Addr,
|
||||
/// Approvals are stored here, as we clear them all upon transfer and cannot accumulate much
|
||||
pub approvals: Vec<Approval>,
|
||||
|
||||
/// Universal resource identifier for this NFT
|
||||
/// Should point to a JSON file that conforms to the ERC721
|
||||
/// Metadata JSON Schema
|
||||
pub token_uri: Option<String>,
|
||||
|
||||
/// You can add any custom metadata here when you extend cw721-base
|
||||
pub extension: T,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
|
||||
pub struct Approval {
|
||||
/// Account that can transfer/send the token
|
||||
pub spender: Addr,
|
||||
/// When the Approval expires (maybe Expiration::never)
|
||||
pub expires: Expiration,
|
||||
}
|
||||
|
||||
impl Approval {
|
||||
pub fn is_expired(&self, block: &BlockInfo) -> bool {
|
||||
self.expires.is_expired(block)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TokenIndexes<'a, T>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
{
|
||||
// pk goes to second tuple element
|
||||
pub owner: MultiIndex<'a, (Addr, Vec<u8>), TokenInfo<T>>,
|
||||
}
|
||||
|
||||
impl<'a, T> IndexList<TokenInfo<T>> for TokenIndexes<'a, T>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + Clone,
|
||||
{
|
||||
fn get_indexes(&'_ self) -> Box<dyn Iterator<Item = &'_ dyn Index<TokenInfo<T>>> + '_> {
|
||||
let v: Vec<&dyn Index<TokenInfo<T>>> = vec![&self.owner];
|
||||
Box::new(v.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn token_owner_idx<T>(d: &TokenInfo<T>, k: Vec<u8>) -> (Addr, Vec<u8>) {
|
||||
(d.owner.clone(), k)
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
[alias]
|
||||
wasm = "build --release --target wasm32-unknown-unknown"
|
||||
wasm-debug = "build --target wasm32-unknown-unknown"
|
||||
unit-test = "test --lib"
|
||||
schema = "run --example schema"
|
|
@ -1,31 +0,0 @@
|
|||
[package]
|
||||
name = "cw721-wrapped"
|
||||
version = "0.10.1"
|
||||
edition = "2018"
|
||||
description = "Wrapped CW721 token contract"
|
||||
|
||||
exclude = [
|
||||
"artifacts/*",
|
||||
]
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
# for more explicit tests, cargo test --features=backtraces
|
||||
backtraces = ["cosmwasm-std/backtraces"]
|
||||
# use library feature to disable all instantiate/execute/query exports
|
||||
library = []
|
||||
|
||||
[dependencies]
|
||||
cw2 = { version = "0.8.0" }
|
||||
cw721-base = { path = "../../contracts/cw721-base", version = "0.10.0", features = ["library"] }
|
||||
cw721 = { path = "../../packages/cw721", version = "0.10.1" }
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
cosmwasm-storage = { version = "0.16.0" }
|
||||
schemars = "0.8.6"
|
||||
serde = { version = "1.0.130", default-features = false, features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cosmwasm-schema = { version = "1.0.0-beta2" }
|
|
@ -1,59 +0,0 @@
|
|||
use std::{
|
||||
env::current_dir,
|
||||
fs::create_dir_all,
|
||||
};
|
||||
|
||||
use cosmwasm_schema::{
|
||||
export_schema,
|
||||
export_schema_with_title,
|
||||
remove_schemas,
|
||||
schema_for,
|
||||
};
|
||||
|
||||
use cw721::{
|
||||
AllNftInfoResponse,
|
||||
ApprovalResponse,
|
||||
ApprovalsResponse,
|
||||
ContractInfoResponse,
|
||||
NftInfoResponse,
|
||||
NumTokensResponse,
|
||||
OperatorsResponse,
|
||||
OwnerOfResponse,
|
||||
TokensResponse,
|
||||
};
|
||||
use cw721_base::{
|
||||
ExecuteMsg,
|
||||
Extension,
|
||||
InstantiateMsg,
|
||||
MinterResponse,
|
||||
QueryMsg,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let mut out_dir = current_dir().unwrap();
|
||||
out_dir.push("schema");
|
||||
create_dir_all(&out_dir).unwrap();
|
||||
remove_schemas(&out_dir).unwrap();
|
||||
|
||||
export_schema(&schema_for!(InstantiateMsg), &out_dir);
|
||||
export_schema_with_title(&schema_for!(ExecuteMsg<()>), &out_dir, "ExecuteMsg");
|
||||
export_schema(&schema_for!(QueryMsg), &out_dir);
|
||||
export_schema_with_title(
|
||||
&schema_for!(AllNftInfoResponse<Extension>),
|
||||
&out_dir,
|
||||
"AllNftInfoResponse",
|
||||
);
|
||||
export_schema(&schema_for!(ApprovalResponse), &out_dir);
|
||||
export_schema(&schema_for!(ApprovalsResponse), &out_dir);
|
||||
export_schema(&schema_for!(OperatorsResponse), &out_dir);
|
||||
export_schema(&schema_for!(ContractInfoResponse), &out_dir);
|
||||
export_schema(&schema_for!(MinterResponse), &out_dir);
|
||||
export_schema_with_title(
|
||||
&schema_for!(NftInfoResponse<Extension>),
|
||||
&out_dir,
|
||||
"NftInfoResponse",
|
||||
);
|
||||
export_schema(&schema_for!(NumTokensResponse), &out_dir);
|
||||
export_schema(&schema_for!(OwnerOfResponse), &out_dir);
|
||||
export_schema(&schema_for!(TokensResponse), &out_dir);
|
||||
}
|
|
@ -1,234 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "AllNftInfoResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"access",
|
||||
"info"
|
||||
],
|
||||
"properties": {
|
||||
"access": {
|
||||
"description": "Who can transfer the token",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/OwnerOfResponse"
|
||||
}
|
||||
]
|
||||
},
|
||||
"info": {
|
||||
"description": "Data on the token itself,",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/NftInfoResponse_for_Nullable_Metadata"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Metadata": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"animation_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"attributes": {
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Trait"
|
||||
}
|
||||
},
|
||||
"background_color": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"external_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"image": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"image_data": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"youtube_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"NftInfoResponse_for_Nullable_Metadata": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "You can add any custom metadata here when you extend cw721-base",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Metadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"OwnerOfResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"description": "If set this address is approved to transfer/send the token as well",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"owner": {
|
||||
"description": "Owner of the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Trait": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"trait_type",
|
||||
"value"
|
||||
],
|
||||
"properties": {
|
||||
"display_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"trait_type": {
|
||||
"type": "string"
|
||||
},
|
||||
"value": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,94 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ApprovalResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approval"
|
||||
],
|
||||
"properties": {
|
||||
"approval": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ApprovalsResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ContractInfoResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"symbol"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"symbol": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,389 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ExecuteMsg",
|
||||
"description": "This is like Cw721ExecuteMsg but we add a Mint command for an owner to make this stand-alone. You will likely want to remove mint and use other control logic in any contract that inherits this.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Transfer is a base message to move a token to another account without triggering actions",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"transfer_nft"
|
||||
],
|
||||
"properties": {
|
||||
"transfer_nft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"recipient",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"recipient": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Send is a base message to transfer a token to a contract and trigger an action on the receiving contract.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"send_nft"
|
||||
],
|
||||
"properties": {
|
||||
"send_nft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"contract",
|
||||
"msg",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"contract": {
|
||||
"type": "string"
|
||||
},
|
||||
"msg": {
|
||||
"$ref": "#/definitions/Binary"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Allows operator to transfer / send the token from the owner's account. If expiration is set, then this allowance has a time/height limit",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approve"
|
||||
],
|
||||
"properties": {
|
||||
"approve": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Remove previously granted Approval",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"revoke"
|
||||
],
|
||||
"properties": {
|
||||
"revoke": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Allows operator to transfer / send any token from the owner's account. If expiration is set, then this allowance has a time/height limit",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approve_all"
|
||||
],
|
||||
"properties": {
|
||||
"approve_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"operator": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Remove previously granted ApproveAll permission",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"revoke_all"
|
||||
],
|
||||
"properties": {
|
||||
"revoke_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator"
|
||||
],
|
||||
"properties": {
|
||||
"operator": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Mint a new NFT, can only be called by the contract minter",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"mint"
|
||||
],
|
||||
"properties": {
|
||||
"mint": {
|
||||
"$ref": "#/definitions/MintMsg_for_Nullable_Metadata"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Burn an NFT the sender has access to",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"burn"
|
||||
],
|
||||
"properties": {
|
||||
"burn": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
],
|
||||
"definitions": {
|
||||
"Binary": {
|
||||
"description": "Binary is a wrapper around Vec<u8> to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec<u8>",
|
||||
"type": "string"
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Metadata": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"animation_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"attributes": {
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Trait"
|
||||
}
|
||||
},
|
||||
"background_color": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"external_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"image": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"image_data": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"youtube_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"MintMsg_for_Nullable_Metadata": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "Any custom extension used by this contract",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Metadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"owner": {
|
||||
"description": "The owner of the newly minter NFT",
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"description": "Unique ID of the NFT",
|
||||
"type": "string"
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Trait": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"trait_type",
|
||||
"value"
|
||||
],
|
||||
"properties": {
|
||||
"display_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"trait_type": {
|
||||
"type": "string"
|
||||
},
|
||||
"value": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "InstantiateMsg",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"minter",
|
||||
"name",
|
||||
"symbol"
|
||||
],
|
||||
"properties": {
|
||||
"minter": {
|
||||
"description": "The minter is the only one who can create new NFTs. This is designed for a base NFT that is controlled by an external program or contract. You will likely replace this with custom logic in custom NFTs",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name of the NFT contract",
|
||||
"type": "string"
|
||||
},
|
||||
"symbol": {
|
||||
"description": "Symbol of the NFT contract",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "MinterResponse",
|
||||
"description": "Shows who can mint these tokens",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"minter"
|
||||
],
|
||||
"properties": {
|
||||
"minter": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,110 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NftInfoResponse",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "You can add any custom metadata here when you extend cw721-base",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Metadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Metadata": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"animation_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"attributes": {
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Trait"
|
||||
}
|
||||
},
|
||||
"background_color": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"external_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"image": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"image_data": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"youtube_url": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Trait": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"trait_type",
|
||||
"value"
|
||||
],
|
||||
"properties": {
|
||||
"display_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"trait_type": {
|
||||
"type": "string"
|
||||
},
|
||||
"value": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NumTokensResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"count"
|
||||
],
|
||||
"properties": {
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "OperatorsResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operators"
|
||||
],
|
||||
"properties": {
|
||||
"operators": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,103 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "OwnerOfResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"description": "If set this address is approved to transfer/send the token as well",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"owner": {
|
||||
"description": "Owner of the token",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,285 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "QueryMsg",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Return the owner of the given token, error if token does not exist Return type: OwnerOfResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner_of"
|
||||
],
|
||||
"properties": {
|
||||
"owner_of": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Return operator that can access all of the owner's tokens. Return type: `ApprovalResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approval"
|
||||
],
|
||||
"properties": {
|
||||
"approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Return approvals that a token has Return type: `ApprovalsResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "List all operators that can access all of the owner's tokens Return type: `OperatorsResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_operators"
|
||||
],
|
||||
"properties": {
|
||||
"all_operators": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired items, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Total number of tokens issued",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"num_tokens"
|
||||
],
|
||||
"properties": {
|
||||
"num_tokens": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns top-level metadata about the contract: `ContractInfoResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"contract_info"
|
||||
],
|
||||
"properties": {
|
||||
"contract_info": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema* but directly from the contract: `NftInfoResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"nft_info"
|
||||
],
|
||||
"properties": {
|
||||
"nft_info": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns the result of both `NftInfo` and `OwnerOf` as one query as an optimization for clients: `AllNftInfo`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_nft_info"
|
||||
],
|
||||
"properties": {
|
||||
"all_nft_info": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With Enumerable extension. Returns all tokens owned by the given address, [] if unset. Return type: TokensResponse.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"tokens"
|
||||
],
|
||||
"properties": {
|
||||
"tokens": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With Enumerable extension. Requires pagination. Lists all token_ids controlled by the contract. Return type: TokensResponse.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_tokens"
|
||||
],
|
||||
"properties": {
|
||||
"all_tokens": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"minter"
|
||||
],
|
||||
"properties": {
|
||||
"minter": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "TokensResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"tokens"
|
||||
],
|
||||
"properties": {
|
||||
"tokens": {
|
||||
"description": "Contains all token_ids in lexicographical ordering If there are more than `limit`, use `start_from` in future queries to achieve pagination.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,203 +0,0 @@
|
|||
pub mod msg;
|
||||
pub mod state;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{
|
||||
Deserialize,
|
||||
Serialize,
|
||||
};
|
||||
|
||||
pub use cosmwasm_std::to_binary;
|
||||
use cosmwasm_std::Empty;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)]
|
||||
pub struct Trait {
|
||||
pub display_type: Option<String>,
|
||||
pub trait_type: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
pub type Extension = Option<Empty>;
|
||||
|
||||
pub type Cw721MetadataContract<'a> = cw721_base::Cw721Contract<'a, Extension, Empty>;
|
||||
pub type ExecuteMsg = cw721_base::ExecuteMsg<Extension>;
|
||||
|
||||
#[cfg(not(feature = "library"))]
|
||||
pub mod entry {
|
||||
|
||||
use std::convert::TryInto;
|
||||
|
||||
use crate::msg::{
|
||||
InstantiateMsg,
|
||||
WrappedAssetInfoResponse,
|
||||
};
|
||||
pub use crate::{
|
||||
msg::QueryMsg,
|
||||
state::{
|
||||
wrapped_asset_info,
|
||||
wrapped_asset_info_read,
|
||||
WrappedAssetInfo,
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
use cosmwasm_std::{
|
||||
entry_point,
|
||||
to_binary,
|
||||
Binary,
|
||||
CosmosMsg,
|
||||
Deps,
|
||||
DepsMut,
|
||||
Env,
|
||||
MessageInfo,
|
||||
Response,
|
||||
StdError,
|
||||
StdResult,
|
||||
WasmMsg,
|
||||
};
|
||||
use cw721::Cw721Query;
|
||||
|
||||
// version info for migration info
|
||||
const CONTRACT_NAME: &str = "crates.io:cw721-wrapped";
|
||||
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
// This is a simple type to let us handle empty extensions
|
||||
|
||||
// This makes a conscious choice on the various generics used by the contract
|
||||
#[entry_point]
|
||||
pub fn instantiate(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
msg: InstantiateMsg,
|
||||
) -> StdResult<Response> {
|
||||
let base = Cw721MetadataContract::default();
|
||||
|
||||
cw2::set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
|
||||
|
||||
let contract_info = cw721::ContractInfoResponse {
|
||||
name: msg.name,
|
||||
symbol: msg.symbol,
|
||||
};
|
||||
base.contract_info.save(deps.storage, &contract_info)?;
|
||||
let minter = deps.api.addr_validate(&msg.minter)?;
|
||||
base.minter.save(deps.storage, &minter)?;
|
||||
|
||||
// save wrapped asset info
|
||||
let data =
|
||||
WrappedAssetInfo {
|
||||
asset_chain: msg.asset_chain,
|
||||
asset_address: msg.asset_address.to_vec().try_into().map_err(
|
||||
|_err| -> StdError {
|
||||
StdError::GenericErr {
|
||||
msg: "WrongSize".to_string(),
|
||||
}
|
||||
},
|
||||
)?,
|
||||
bridge: deps.api.addr_canonicalize(&info.sender.as_str())?,
|
||||
};
|
||||
wrapped_asset_info(deps.storage).save(&data)?;
|
||||
|
||||
if let Some(mint_msg) = msg.mint {
|
||||
execute(deps, env, info, ExecuteMsg::Mint(mint_msg))
|
||||
.map_err(|e| StdError::generic_err(format!("{}", e)))?;
|
||||
}
|
||||
|
||||
if let Some(hook) = msg.init_hook {
|
||||
Ok(
|
||||
Response::new().add_message(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: hook.contract_addr,
|
||||
msg: hook.msg,
|
||||
funds: vec![],
|
||||
})),
|
||||
)
|
||||
} else {
|
||||
Ok(Response::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[entry_point]
|
||||
pub fn execute(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
msg: ExecuteMsg,
|
||||
) -> Result<Response, cw721_base::ContractError> {
|
||||
Cw721MetadataContract::default().execute(deps, env, info, msg)
|
||||
}
|
||||
|
||||
#[entry_point]
|
||||
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
|
||||
let base = Cw721MetadataContract::default();
|
||||
match msg {
|
||||
QueryMsg::WrappedAssetInfo {} => to_binary(&query_wrapped_asset_info(deps)?),
|
||||
QueryMsg::OwnerOf {
|
||||
token_id,
|
||||
include_expired,
|
||||
} => {
|
||||
to_binary(&base.owner_of(deps, env, token_id, include_expired.unwrap_or(false))?)
|
||||
}
|
||||
QueryMsg::Approval {
|
||||
token_id,
|
||||
spender,
|
||||
include_expired,
|
||||
} => to_binary(&base.approval(
|
||||
deps,
|
||||
env,
|
||||
token_id,
|
||||
spender,
|
||||
include_expired.unwrap_or(false),
|
||||
)?),
|
||||
QueryMsg::Approvals {
|
||||
token_id,
|
||||
include_expired,
|
||||
} => {
|
||||
to_binary(&base.approvals(deps, env, token_id, include_expired.unwrap_or(false))?)
|
||||
}
|
||||
QueryMsg::AllOperators {
|
||||
owner,
|
||||
include_expired,
|
||||
start_after,
|
||||
limit,
|
||||
} => to_binary(&base.operators(
|
||||
deps,
|
||||
env,
|
||||
owner,
|
||||
include_expired.unwrap_or(false),
|
||||
start_after,
|
||||
limit,
|
||||
)?),
|
||||
QueryMsg::NumTokens {} => to_binary(&base.num_tokens(deps)?),
|
||||
QueryMsg::Tokens {
|
||||
owner,
|
||||
start_after,
|
||||
limit,
|
||||
} => to_binary(&base.tokens(deps, owner, start_after, limit)?),
|
||||
QueryMsg::AllTokens { start_after, limit } => {
|
||||
to_binary(&base.all_tokens(deps, start_after, limit)?)
|
||||
}
|
||||
QueryMsg::Minter {} => to_binary(&base.minter(deps)?),
|
||||
QueryMsg::ContractInfo {} => to_binary(&base.contract_info(deps)?),
|
||||
QueryMsg::NftInfo { token_id } => to_binary(&base.nft_info(deps, token_id)?),
|
||||
QueryMsg::AllNftInfo {
|
||||
token_id,
|
||||
include_expired,
|
||||
} => to_binary(&base.all_nft_info(
|
||||
deps,
|
||||
env,
|
||||
token_id,
|
||||
include_expired.unwrap_or(false),
|
||||
)?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn query_wrapped_asset_info(deps: Deps) -> StdResult<WrappedAssetInfoResponse> {
|
||||
let info = wrapped_asset_info_read(deps.storage).load()?;
|
||||
Ok(WrappedAssetInfoResponse {
|
||||
asset_chain: info.asset_chain,
|
||||
asset_address: info.asset_address,
|
||||
bridge: deps.api.addr_humanize(&info.bridge)?,
|
||||
})
|
||||
}
|
||||
}
|
|
@ -1,135 +0,0 @@
|
|||
pub use cw721_base::MintMsg;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{
|
||||
Deserialize,
|
||||
Serialize,
|
||||
};
|
||||
|
||||
use cosmwasm_std::{
|
||||
Addr,
|
||||
Binary,
|
||||
Empty,
|
||||
};
|
||||
|
||||
pub use cw721_base::msg::ExecuteMsg;
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
/// The cw721_base crate allows an extension point which we don't care about
|
||||
pub type NoExt = Option<Empty>;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct InstantiateMsg {
|
||||
/// Name of the NFT contract
|
||||
pub name: String,
|
||||
/// Symbol of the NFT contract
|
||||
pub symbol: String,
|
||||
|
||||
/// Native chain of the NFT
|
||||
pub asset_chain: u16,
|
||||
|
||||
/// Native address of the NFT
|
||||
pub asset_address: Binary,
|
||||
|
||||
/// The minter is the only one who can create new NFTs.
|
||||
/// This is designed for a base NFT that is controlled by an external program
|
||||
/// or contract. You will likely replace this with custom logic in custom NFTs
|
||||
pub minter: String,
|
||||
|
||||
/// Mint a new NFT upon creation
|
||||
pub mint: Option<MintMsg<NoExt>>,
|
||||
|
||||
/// Generic callback - used to register the newly instantiated asset
|
||||
pub init_hook: Option<InitHook>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct InitHook {
|
||||
pub msg: Binary,
|
||||
pub contract_addr: HumanAddr,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum QueryMsg {
|
||||
/// Generic information about the wrapped asset
|
||||
WrappedAssetInfo {},
|
||||
|
||||
/// Return the owner of the given token, error if token does not exist
|
||||
/// Return type: OwnerOfResponse
|
||||
OwnerOf {
|
||||
token_id: String,
|
||||
/// unset or false will filter out expired approvals, you must set to true to see them
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// Return operator that can access all of the owner's tokens.
|
||||
/// Return type: `ApprovalResponse`
|
||||
Approval {
|
||||
token_id: String,
|
||||
spender: String,
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// Return approvals that a token has
|
||||
/// Return type: `ApprovalsResponse`
|
||||
Approvals {
|
||||
token_id: String,
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// List all operators that can access all of the owner's tokens
|
||||
/// Return type: `OperatorsResponse`
|
||||
AllOperators {
|
||||
owner: String,
|
||||
/// unset or false will filter out expired items, you must set to true to see them
|
||||
include_expired: Option<bool>,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
},
|
||||
/// Total number of tokens issued
|
||||
NumTokens {},
|
||||
|
||||
/// With MetaData Extension.
|
||||
/// Returns top-level metadata about the contract: `ContractInfoResponse`
|
||||
ContractInfo {},
|
||||
|
||||
/// Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema*
|
||||
/// but directly from the contract: `NftInfoResponse`
|
||||
NftInfo {
|
||||
token_id: String,
|
||||
},
|
||||
|
||||
/// Returns the result of both `NftInfo` and `OwnerOf` as one query as an optimization
|
||||
/// for clients: `AllNftInfo`
|
||||
AllNftInfo {
|
||||
token_id: String,
|
||||
/// unset or false will filter out expired approvals, you must set to true to see them
|
||||
include_expired: Option<bool>,
|
||||
},
|
||||
|
||||
/// Returns all tokens owned by the given address, [] if unset.
|
||||
/// Return type: TokensResponse.
|
||||
Tokens {
|
||||
owner: String,
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
},
|
||||
|
||||
/// Requires pagination. Lists all token_ids controlled by the contract.
|
||||
/// Return type: TokensResponse.
|
||||
AllTokens {
|
||||
start_after: Option<String>,
|
||||
limit: Option<u32>,
|
||||
},
|
||||
|
||||
// Return the minter
|
||||
Minter {},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct WrappedAssetInfoResponse {
|
||||
pub asset_chain: u16, // Asset chain id
|
||||
pub asset_address: Binary, // Asset smart contract address in the original chain
|
||||
pub bridge: Addr, // Bridge address, authorized to mint and burn wrapped tokens
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
use schemars::JsonSchema;
|
||||
use serde::{
|
||||
Deserialize,
|
||||
Serialize,
|
||||
};
|
||||
|
||||
use cosmwasm_std::{
|
||||
Binary,
|
||||
CanonicalAddr,
|
||||
Storage,
|
||||
};
|
||||
use cosmwasm_storage::{
|
||||
singleton,
|
||||
singleton_read,
|
||||
ReadonlySingleton,
|
||||
Singleton,
|
||||
};
|
||||
|
||||
pub const KEY_WRAPPED_ASSET: &[u8] = b"wrappedAsset";
|
||||
|
||||
// Created at initialization and reference original asset and bridge address
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct WrappedAssetInfo {
|
||||
pub asset_chain: u16, // Asset chain id
|
||||
pub asset_address: Binary, // Asset smart contract address on the original chain
|
||||
pub bridge: CanonicalAddr, // Bridge address, authorized to mint and burn wrapped tokens
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_info(storage: &mut dyn Storage) -> Singleton<WrappedAssetInfo> {
|
||||
singleton(storage, KEY_WRAPPED_ASSET)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_info_read(storage: &dyn Storage) -> ReadonlySingleton<WrappedAssetInfo> {
|
||||
singleton_read(storage, KEY_WRAPPED_ASSET)
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
[package]
|
||||
name = "mock-bridge-integration"
|
||||
name = "mock-bridge-integration-2"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
description = "Mock Bridge Integration for Transfer w/ Payload"
|
||||
|
@ -13,15 +13,15 @@ backtraces = ["cosmwasm-std/backtraces"]
|
|||
library = []
|
||||
|
||||
[dependencies]
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
cosmwasm-storage = { version = "0.16.0" }
|
||||
schemars = "0.8.1"
|
||||
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
|
||||
cw20 = "0.8.0"
|
||||
cw20-base = { version = "0.8.0", features = ["library"] }
|
||||
cw20-wrapped = { path = "../cw20-wrapped", features = ["library"] }
|
||||
terraswap = "2.4.0"
|
||||
thiserror = { version = "1.0.20" }
|
||||
cosmwasm-std = { version = "1.0.0" }
|
||||
cosmwasm-storage = { version = "1.0.0" }
|
||||
schemars = "0.8.8"
|
||||
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
|
||||
cw20 = "0.13.2"
|
||||
cw20-base = { version = "0.13.2", features = ["library"] }
|
||||
cw20-wrapped-2 = { path = "../cw20-wrapped", features = ["library"] }
|
||||
terraswap = "2.6.1"
|
||||
thiserror = { version = "1.0.31" }
|
||||
k256 = { version = "0.9.4", default-features = false, features = ["ecdsa"] }
|
||||
sha3 = { version = "0.9.1", default-features = false }
|
||||
generic-array = { version = "0.14.4" }
|
||||
|
@ -29,9 +29,9 @@ hex = "0.4.2"
|
|||
lazy_static = "1.4.0"
|
||||
bigint = "4"
|
||||
|
||||
wormhole-bridge-terra = { path = "../wormhole", features = ["library"] }
|
||||
token-bridge-terra = { path = "../token-bridge", features = ["library"] }
|
||||
wormhole-bridge-terra-2 = { path = "../wormhole", features = ["library"] }
|
||||
token-bridge-terra-2 = { path = "../token-bridge", features = ["library"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cosmwasm-vm = { version = "0.16.0", default-features = false }
|
||||
cosmwasm-vm = { version = "1.0.0", default-features = false }
|
||||
serde_json = "1.0"
|
||||
|
|
|
@ -31,7 +31,7 @@ use crate::{
|
|||
},
|
||||
};
|
||||
|
||||
use token_bridge_terra::{
|
||||
use token_bridge_terra_2::{
|
||||
msg::{
|
||||
ExecuteMsg as TokenBridgeExecuteMsg,
|
||||
QueryMsg as TokenBridgeQueryMessage,
|
||||
|
@ -79,7 +79,7 @@ pub fn query(_deps: Deps, _env: Env, _msg: QueryMsg) -> StdResult<Binary> {
|
|||
}
|
||||
|
||||
fn complete_transfer_with_payload(
|
||||
mut deps: DepsMut,
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
info: MessageInfo,
|
||||
data: &Binary,
|
||||
|
@ -117,4 +117,4 @@ fn parse_transfer_vaa(
|
|||
})?,
|
||||
}))?;
|
||||
Ok(transfer_info)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
[alias]
|
||||
wasm = "build --release --target wasm32-unknown-unknown"
|
||||
wasm-debug = "build --target wasm32-unknown-unknown"
|
||||
unit-test = "test --lib --features backtraces"
|
||||
integration-test = "test --test integration"
|
|
@ -1,30 +0,0 @@
|
|||
[package]
|
||||
name = "nft-bridge"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
description = "Wormhole NFT bridge"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
backtraces = ["cosmwasm-std/backtraces"]
|
||||
# use library feature to disable all init/handle/query exports
|
||||
library = []
|
||||
|
||||
[dependencies]
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
cosmwasm-storage = { version = "0.16.0" }
|
||||
schemars = "0.8.1"
|
||||
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
|
||||
cw721-wrapped = { path = "../cw721-wrapped", features = ["library"] }
|
||||
cw721-base = { path = "../../contracts/cw721-base", version = "0.10.0", features = ["library"] }
|
||||
cw721 = { path = "../../packages/cw721" }
|
||||
wormhole-bridge-terra = { path = "../wormhole", features = ["library"] }
|
||||
sha3 = { version = "0.9.1", default-features = false }
|
||||
hex = "0.4.2"
|
||||
bigint = "4"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1.0"
|
||||
lazy_static = "1.4.0"
|
|
@ -1,589 +0,0 @@
|
|||
use crate::{
|
||||
msg::WrappedRegistryResponse,
|
||||
state::{
|
||||
spl_cache,
|
||||
spl_cache_read,
|
||||
wrapped_asset,
|
||||
BoundedVec,
|
||||
SplCacheItem,
|
||||
},
|
||||
token_id::{
|
||||
from_external_token_id,
|
||||
to_external_token_id,
|
||||
},
|
||||
CHAIN_ID,
|
||||
};
|
||||
use cosmwasm_std::{
|
||||
entry_point,
|
||||
to_binary,
|
||||
Binary,
|
||||
CanonicalAddr,
|
||||
CosmosMsg,
|
||||
Deps,
|
||||
DepsMut,
|
||||
Empty,
|
||||
Env,
|
||||
MessageInfo,
|
||||
QueryRequest,
|
||||
Response,
|
||||
StdError,
|
||||
StdResult,
|
||||
WasmMsg,
|
||||
WasmQuery, Order,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
msg::{
|
||||
ExecuteMsg,
|
||||
InstantiateMsg,
|
||||
MigrateMsg,
|
||||
QueryMsg,
|
||||
},
|
||||
state::{
|
||||
bridge_contracts,
|
||||
bridge_contracts_read,
|
||||
config,
|
||||
config_read,
|
||||
wrapped_asset_address,
|
||||
wrapped_asset_address_read,
|
||||
wrapped_asset_read,
|
||||
Action,
|
||||
ConfigInfo,
|
||||
RegisterChain,
|
||||
TokenBridgeMessage,
|
||||
TransferInfo,
|
||||
UpgradeContract,
|
||||
},
|
||||
};
|
||||
use wormhole::{
|
||||
byte_utils::{
|
||||
extend_address_to_32,
|
||||
extend_address_to_32_array,
|
||||
get_string_from_32,
|
||||
string_to_array,
|
||||
ByteUtils,
|
||||
},
|
||||
error::ContractError,
|
||||
};
|
||||
|
||||
use wormhole::msg::{
|
||||
ExecuteMsg as WormholeExecuteMsg,
|
||||
QueryMsg as WormholeQueryMsg,
|
||||
};
|
||||
|
||||
use wormhole::state::{
|
||||
vaa_archive_add,
|
||||
vaa_archive_check,
|
||||
GovernancePacket,
|
||||
ParsedVAA,
|
||||
};
|
||||
|
||||
use sha3::{
|
||||
Digest,
|
||||
Keccak256,
|
||||
};
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
const WRAPPED_ASSET_UPDATING: &str = "updating";
|
||||
|
||||
#[cfg_attr(not(feature = "library"), entry_point)]
|
||||
pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> {
|
||||
Ok(Response::new())
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "library"), entry_point)]
|
||||
pub fn instantiate(
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
_info: MessageInfo,
|
||||
msg: InstantiateMsg,
|
||||
) -> StdResult<Response> {
|
||||
// Save general wormhole info
|
||||
let state = ConfigInfo {
|
||||
gov_chain: msg.gov_chain,
|
||||
gov_address: msg.gov_address.as_slice().to_vec(),
|
||||
wormhole_contract: msg.wormhole_contract,
|
||||
wrapped_asset_code_id: msg.wrapped_asset_code_id,
|
||||
};
|
||||
config(deps.storage).save(&state)?;
|
||||
|
||||
Ok(Response::default())
|
||||
}
|
||||
|
||||
pub fn parse_vaa(deps: DepsMut, block_time: u64, data: &Binary) -> StdResult<ParsedVAA> {
|
||||
let cfg = config_read(deps.storage).load()?;
|
||||
let vaa: ParsedVAA = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
|
||||
contract_addr: cfg.wormhole_contract,
|
||||
msg: to_binary(&WormholeQueryMsg::VerifyVAA {
|
||||
vaa: data.clone(),
|
||||
block_time,
|
||||
})?,
|
||||
}))?;
|
||||
Ok(vaa)
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "library"), entry_point)]
|
||||
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {
|
||||
match msg {
|
||||
ExecuteMsg::InitiateTransfer {
|
||||
contract_addr,
|
||||
token_id,
|
||||
recipient_chain,
|
||||
recipient,
|
||||
nonce,
|
||||
} => handle_initiate_transfer(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
contract_addr,
|
||||
token_id,
|
||||
recipient_chain,
|
||||
recipient.to_array()?,
|
||||
nonce,
|
||||
),
|
||||
ExecuteMsg::SubmitVaa { data } => submit_vaa(deps, env, info, &data),
|
||||
ExecuteMsg::RegisterAssetHook { asset_id } => {
|
||||
handle_register_asset(deps, env, info, asset_id.as_slice())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn submit_vaa(
|
||||
mut deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
data: &Binary,
|
||||
) -> StdResult<Response> {
|
||||
let state = config_read(deps.storage).load()?;
|
||||
|
||||
let vaa = parse_vaa(deps.branch(), env.block.time.seconds(), data)?;
|
||||
let data = vaa.payload;
|
||||
|
||||
if vaa_archive_check(deps.storage, vaa.hash.as_slice()) {
|
||||
return ContractError::VaaAlreadyExecuted.std_err();
|
||||
}
|
||||
vaa_archive_add(deps.storage, vaa.hash.as_slice())?;
|
||||
|
||||
// check if vaa is from governance
|
||||
if state.gov_chain == vaa.emitter_chain && state.gov_address == vaa.emitter_address {
|
||||
return handle_governance_payload(deps, env, &data);
|
||||
}
|
||||
|
||||
let message = TokenBridgeMessage::deserialize(&data)?;
|
||||
|
||||
match message.action {
|
||||
Action::TRANSFER => handle_complete_transfer(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
vaa.emitter_chain,
|
||||
vaa.emitter_address,
|
||||
TransferInfo::deserialize(&message.payload)?,
|
||||
),
|
||||
_ => ContractError::InvalidVAAAction.std_err(),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_governance_payload(deps: DepsMut, env: Env, data: &[u8]) -> StdResult<Response> {
|
||||
let gov_packet = GovernancePacket::deserialize(data)?;
|
||||
let module = get_string_from_32(&gov_packet.module);
|
||||
|
||||
if module != "NFTBridge" {
|
||||
return Err(StdError::generic_err("this is not a valid module"));
|
||||
}
|
||||
|
||||
if gov_packet.chain != 0 && gov_packet.chain != CHAIN_ID {
|
||||
return Err(StdError::generic_err(
|
||||
"the governance VAA is for another chain",
|
||||
));
|
||||
}
|
||||
|
||||
match gov_packet.action {
|
||||
1u8 => handle_register_chain(deps, env, RegisterChain::deserialize(&gov_packet.payload)?),
|
||||
2u8 => handle_upgrade_contract(
|
||||
deps,
|
||||
env,
|
||||
UpgradeContract::deserialize(&gov_packet.payload)?,
|
||||
),
|
||||
_ => ContractError::InvalidVAAAction.std_err(),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_upgrade_contract(
|
||||
_deps: DepsMut,
|
||||
env: Env,
|
||||
upgrade_contract: UpgradeContract,
|
||||
) -> StdResult<Response> {
|
||||
Ok(Response::new()
|
||||
.add_message(CosmosMsg::Wasm(WasmMsg::Migrate {
|
||||
contract_addr: env.contract.address.to_string(),
|
||||
new_code_id: upgrade_contract.new_contract,
|
||||
msg: to_binary(&MigrateMsg {})?,
|
||||
}))
|
||||
.add_attribute("action", "contract_upgrade"))
|
||||
}
|
||||
|
||||
fn handle_register_chain(
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
register_chain: RegisterChain,
|
||||
) -> StdResult<Response> {
|
||||
let RegisterChain {
|
||||
chain_id,
|
||||
chain_address,
|
||||
} = register_chain;
|
||||
|
||||
let existing = bridge_contracts_read(deps.storage).load(&chain_id.to_be_bytes());
|
||||
if existing.is_ok() {
|
||||
return Err(StdError::generic_err(
|
||||
"bridge contract already exists for this chain",
|
||||
));
|
||||
}
|
||||
|
||||
let mut bucket = bridge_contracts(deps.storage);
|
||||
bucket.save(&chain_id.to_be_bytes(), &chain_address)?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("chain_id", chain_id.to_string())
|
||||
.add_attribute("chain_address", hex::encode(chain_address)))
|
||||
}
|
||||
|
||||
fn handle_complete_transfer(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
_info: MessageInfo,
|
||||
emitter_chain: u16,
|
||||
emitter_address: Vec<u8>,
|
||||
transfer_info: TransferInfo,
|
||||
) -> StdResult<Response> {
|
||||
let cfg = config_read(deps.storage).load()?;
|
||||
|
||||
let expected_contract =
|
||||
bridge_contracts_read(deps.storage).load(&emitter_chain.to_be_bytes())?;
|
||||
|
||||
// must be sent by a registered token bridge contract
|
||||
if expected_contract != emitter_address {
|
||||
return Err(StdError::generic_err("invalid emitter"));
|
||||
}
|
||||
|
||||
if transfer_info.recipient_chain != CHAIN_ID {
|
||||
return Err(StdError::generic_err(
|
||||
"this transfer is not directed at this chain",
|
||||
));
|
||||
}
|
||||
|
||||
let token_chain = transfer_info.nft_chain;
|
||||
let target_address = &(&transfer_info.recipient[..]).get_address(0);
|
||||
|
||||
let mut messages = vec![];
|
||||
|
||||
let recipient = deps
|
||||
.api
|
||||
.addr_humanize(target_address)
|
||||
.or_else(|_| ContractError::WrongTargetAddressFormat.std_err())?;
|
||||
|
||||
let contract_addr;
|
||||
|
||||
let token_id = from_external_token_id(
|
||||
deps.storage,
|
||||
token_chain,
|
||||
&transfer_info.nft_address,
|
||||
&transfer_info.token_id,
|
||||
)?;
|
||||
|
||||
if token_chain != CHAIN_ID {
|
||||
// NFT is not native to this chain, so we need a wrapper
|
||||
let asset_address = transfer_info.nft_address;
|
||||
let asset_id = build_asset_id(token_chain, &asset_address);
|
||||
|
||||
let token_uri = String::from_utf8(transfer_info.uri.to_vec())
|
||||
.map_err(|_| StdError::generic_err("could not parse uri string"))?;
|
||||
|
||||
let mint_msg = cw721_base::msg::MintMsg {
|
||||
token_id,
|
||||
owner: recipient.to_string(),
|
||||
token_uri: Some(token_uri),
|
||||
extension: None,
|
||||
};
|
||||
|
||||
// Check if this asset is already deployed
|
||||
if let Ok(wrapped_addr) = wrapped_asset_read(deps.storage).load(&asset_id) {
|
||||
contract_addr = wrapped_addr;
|
||||
// Asset already deployed, just mint
|
||||
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_addr.clone(),
|
||||
msg: to_binary(&cw721_base::msg::ExecuteMsg::Mint(mint_msg))?,
|
||||
funds: vec![],
|
||||
}));
|
||||
} else {
|
||||
contract_addr = env.contract.address.clone().into_string();
|
||||
wrapped_asset(deps.storage)
|
||||
.save(&asset_id, &HumanAddr::from(WRAPPED_ASSET_UPDATING))?;
|
||||
|
||||
let (name, symbol) = if token_chain == 1 {
|
||||
let spl_cache_item = SplCacheItem {
|
||||
name: transfer_info.name,
|
||||
symbol: transfer_info.symbol,
|
||||
};
|
||||
spl_cache(deps.storage).save(&transfer_info.token_id, &spl_cache_item)?;
|
||||
// Solana NFTs all use the same NFT contract, so unify the name
|
||||
(
|
||||
"Wormhole Bridged Solana-NFT".to_string(),
|
||||
"WORMSPLNFT".to_string(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
get_string_from_32(&transfer_info.name),
|
||||
get_string_from_32(&transfer_info.symbol),
|
||||
)
|
||||
};
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Instantiate {
|
||||
admin: Some(contract_addr.clone()),
|
||||
code_id: cfg.wrapped_asset_code_id,
|
||||
msg: to_binary(&cw721_wrapped::msg::InstantiateMsg {
|
||||
name,
|
||||
symbol,
|
||||
asset_chain: token_chain,
|
||||
asset_address: (&transfer_info.nft_address[..]).into(),
|
||||
minter: env.contract.address.into_string(),
|
||||
mint: Some(mint_msg),
|
||||
init_hook: Some(cw721_wrapped::msg::InitHook {
|
||||
msg: cw721_wrapped::to_binary(&ExecuteMsg::RegisterAssetHook {
|
||||
asset_id: asset_id.to_vec().into(),
|
||||
})
|
||||
.map_err(|_| StdError::generic_err("couldn't convert to binary"))?,
|
||||
contract_addr: contract_addr.clone(),
|
||||
}),
|
||||
})?,
|
||||
funds: vec![],
|
||||
label: String::new(),
|
||||
}));
|
||||
}
|
||||
} else {
|
||||
// Native NFT, transfer from custody
|
||||
let token_address = (&transfer_info.nft_address[..]).get_address(0);
|
||||
|
||||
contract_addr = deps.api.addr_humanize(&token_address)?.to_string();
|
||||
|
||||
messages.push(CosmosMsg::<Empty>::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_addr.clone(),
|
||||
msg: to_binary(&cw721_base::msg::ExecuteMsg::<Option<Empty>>::TransferNft {
|
||||
recipient: recipient.to_string(),
|
||||
token_id,
|
||||
})?,
|
||||
funds: vec![],
|
||||
}));
|
||||
}
|
||||
Ok(Response::new()
|
||||
.add_messages(messages)
|
||||
.add_attribute("action", "complete_transfer")
|
||||
.add_attribute("recipient", recipient)
|
||||
.add_attribute("contract", contract_addr))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn handle_initiate_transfer(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
asset: HumanAddr,
|
||||
token_id: String,
|
||||
recipient_chain: u16,
|
||||
recipient: [u8; 32],
|
||||
nonce: u32,
|
||||
) -> StdResult<Response> {
|
||||
if recipient_chain == CHAIN_ID {
|
||||
return ContractError::SameSourceAndTarget.std_err();
|
||||
}
|
||||
|
||||
let asset_chain: u16;
|
||||
let asset_address: [u8; 32];
|
||||
|
||||
let cfg: ConfigInfo = config_read(deps.storage).load()?;
|
||||
let asset_canonical: CanonicalAddr = deps.api.addr_canonicalize(&asset)?;
|
||||
|
||||
let mut messages: Vec<CosmosMsg> = vec![];
|
||||
|
||||
if wrapped_asset_address_read(deps.storage).load(asset_canonical.as_slice()).is_ok() {
|
||||
// This is a deployed wrapped asset, burn it
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: asset.clone(),
|
||||
msg: to_binary(&cw721_wrapped::msg::ExecuteMsg::Burn::<Option<Empty>> {
|
||||
token_id: token_id.clone(),
|
||||
})?,
|
||||
funds: vec![],
|
||||
}));
|
||||
|
||||
let wrapped_token_info: cw721_wrapped::msg::WrappedAssetInfoResponse = deps
|
||||
.querier
|
||||
.custom_query(&QueryRequest::<Empty>::Wasm(WasmQuery::Smart {
|
||||
contract_addr: asset.clone(),
|
||||
msg: to_binary(&cw721_wrapped::msg::QueryMsg::WrappedAssetInfo {})?,
|
||||
}))?;
|
||||
|
||||
asset_address = wrapped_token_info.asset_address.to_array()?;
|
||||
asset_chain = wrapped_token_info.asset_chain;
|
||||
} else {
|
||||
// Native NFT, lock it up
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: asset.clone(),
|
||||
msg: to_binary(&cw721_base::msg::ExecuteMsg::<Option<Empty>>::TransferNft {
|
||||
recipient: env.contract.address.to_string(),
|
||||
token_id: token_id.clone(),
|
||||
})?,
|
||||
funds: vec![],
|
||||
}));
|
||||
|
||||
asset_chain = CHAIN_ID;
|
||||
asset_address = extend_address_to_32_array(&asset_canonical);
|
||||
};
|
||||
|
||||
let external_token_id =
|
||||
to_external_token_id(deps.storage, asset_chain, &asset_address, token_id.clone())?;
|
||||
|
||||
let symbol: [u8; 32];
|
||||
let name: [u8; 32];
|
||||
|
||||
if asset_chain == 1 {
|
||||
let SplCacheItem {
|
||||
name: cached_name,
|
||||
symbol: cached_symbol,
|
||||
} = spl_cache_read(deps.storage).load(&external_token_id)?;
|
||||
symbol = cached_symbol;
|
||||
name = cached_name;
|
||||
} else {
|
||||
let response: cw721::ContractInfoResponse =
|
||||
deps.querier
|
||||
.custom_query(&QueryRequest::<Empty>::Wasm(WasmQuery::Smart {
|
||||
contract_addr: asset.clone(),
|
||||
msg: to_binary(&cw721_base::msg::QueryMsg::ContractInfo {})?,
|
||||
}))?;
|
||||
name = string_to_array(&response.name);
|
||||
symbol = string_to_array(&response.symbol);
|
||||
}
|
||||
|
||||
let cw721::NftInfoResponse::<Option<Empty>> { token_uri, .. } =
|
||||
deps.querier
|
||||
.custom_query(&QueryRequest::<Empty>::Wasm(WasmQuery::Smart {
|
||||
contract_addr: asset,
|
||||
msg: to_binary(&cw721_base::msg::QueryMsg::NftInfo {
|
||||
token_id: token_id.clone(),
|
||||
})?,
|
||||
}))?;
|
||||
|
||||
let transfer_info = TransferInfo {
|
||||
nft_address: asset_address,
|
||||
nft_chain: asset_chain,
|
||||
symbol,
|
||||
name,
|
||||
token_id: external_token_id,
|
||||
uri: BoundedVec::new(token_uri.unwrap().into())?,
|
||||
recipient,
|
||||
recipient_chain,
|
||||
};
|
||||
|
||||
let token_bridge_message = TokenBridgeMessage {
|
||||
action: Action::TRANSFER,
|
||||
payload: transfer_info.serialize(),
|
||||
};
|
||||
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: cfg.wormhole_contract,
|
||||
msg: to_binary(&WormholeExecuteMsg::PostMessage {
|
||||
message: Binary::from(token_bridge_message.serialize()),
|
||||
nonce,
|
||||
})?,
|
||||
funds: vec![],
|
||||
}));
|
||||
|
||||
Ok(Response::new()
|
||||
.add_messages(messages)
|
||||
.add_attribute("transfer.token_chain", asset_chain.to_string())
|
||||
.add_attribute("transfer.token", hex::encode(asset_address))
|
||||
.add_attribute("transfer.token_id", token_id)
|
||||
.add_attribute("transfer.external_token_id", hex::encode(external_token_id))
|
||||
.add_attribute(
|
||||
"transfer.sender",
|
||||
hex::encode(extend_address_to_32(
|
||||
&deps.api.addr_canonicalize(info.sender.as_str())?,
|
||||
)),
|
||||
)
|
||||
.add_attribute("transfer.recipient_chain", recipient_chain.to_string())
|
||||
.add_attribute("transfer.recipient", hex::encode(recipient))
|
||||
.add_attribute("transfer.nonce", nonce.to_string())
|
||||
.add_attribute("transfer.block_time", env.block.time.seconds().to_string()))
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "library"), entry_point)]
|
||||
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
|
||||
match msg {
|
||||
QueryMsg::WrappedRegistry { chain, address } => {
|
||||
to_binary(&query_wrapped_registry(deps, chain, address.as_slice())?)
|
||||
}
|
||||
QueryMsg::AllWrappedAssets { } => {
|
||||
to_binary(&query_all_wrapped_assets(deps)?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle wrapped asset registration messages
|
||||
fn handle_register_asset(
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
info: MessageInfo,
|
||||
asset_id: &[u8],
|
||||
) -> StdResult<Response> {
|
||||
let mut bucket = wrapped_asset(deps.storage);
|
||||
let result = bucket
|
||||
.load(asset_id)
|
||||
.map_err(|_| ContractError::RegistrationForbidden.std())?;
|
||||
if result != WRAPPED_ASSET_UPDATING {
|
||||
return ContractError::AssetAlreadyRegistered.std_err();
|
||||
}
|
||||
|
||||
bucket.save(asset_id, &info.sender.to_string())?;
|
||||
|
||||
let contract_address: CanonicalAddr = deps.api.addr_canonicalize(info.sender.as_str())?;
|
||||
wrapped_asset_address(deps.storage).save(contract_address.as_slice(), &asset_id.to_vec())?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "register_asset")
|
||||
.add_attribute("asset_id", format!("{:?}", asset_id))
|
||||
.add_attribute("contract_addr", info.sender))
|
||||
}
|
||||
|
||||
pub fn query_wrapped_registry(
|
||||
deps: Deps,
|
||||
chain: u16,
|
||||
address: &[u8],
|
||||
) -> StdResult<WrappedRegistryResponse> {
|
||||
let asset_id = build_asset_id(chain, address);
|
||||
// Check if this asset is already deployed
|
||||
match wrapped_asset_read(deps.storage).load(&asset_id) {
|
||||
Ok(address) => Ok(WrappedRegistryResponse { address }),
|
||||
Err(_) => ContractError::AssetNotFound.std_err(),
|
||||
}
|
||||
}
|
||||
|
||||
fn query_all_wrapped_assets(deps: Deps) -> StdResult<Vec<String>> {
|
||||
let bucket = wrapped_asset_address_read(deps.storage);
|
||||
let mut result = vec![];
|
||||
for item in bucket.range(None, None, Order::Ascending) {
|
||||
let contract_address = item?.0.into();
|
||||
result.push(deps.api.addr_humanize(&contract_address)?.to_string())
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
|
||||
fn build_asset_id(chain: u16, address: &[u8]) -> Vec<u8> {
|
||||
let mut asset_id: Vec<u8> = vec![];
|
||||
asset_id.extend_from_slice(&chain.to_be_bytes());
|
||||
asset_id.extend_from_slice(address);
|
||||
|
||||
let mut hasher = Keccak256::new();
|
||||
hasher.update(asset_id);
|
||||
hasher.finalize().to_vec()
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
pub mod contract;
|
||||
pub mod msg;
|
||||
pub mod state;
|
||||
pub mod token_id;
|
||||
|
||||
// Chain ID of Terra
|
||||
const CHAIN_ID: u16 = 3;
|
|
@ -1,61 +0,0 @@
|
|||
use cosmwasm_std::Binary;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{
|
||||
Deserialize,
|
||||
Serialize,
|
||||
};
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct InstantiateMsg {
|
||||
// governance contract details
|
||||
pub gov_chain: u16,
|
||||
pub gov_address: Binary,
|
||||
|
||||
pub wormhole_contract: HumanAddr,
|
||||
pub wrapped_asset_code_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ExecuteMsg {
|
||||
RegisterAssetHook {
|
||||
asset_id: Binary,
|
||||
},
|
||||
|
||||
InitiateTransfer {
|
||||
contract_addr: String,
|
||||
token_id: String,
|
||||
recipient_chain: u16,
|
||||
recipient: Binary,
|
||||
nonce: u32,
|
||||
},
|
||||
|
||||
SubmitVaa {
|
||||
data: Binary,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub struct MigrateMsg {}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum QueryMsg {
|
||||
WrappedRegistry { chain: u16, address: Binary },
|
||||
AllWrappedAssets { },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub struct WrappedRegistryResponse {
|
||||
pub address: HumanAddr,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WormholeQueryMsg {
|
||||
VerifyVAA { vaa: Binary, block_time: u64 },
|
||||
}
|
|
@ -1,272 +0,0 @@
|
|||
use std::convert::TryInto;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{
|
||||
Deserialize,
|
||||
Serialize,
|
||||
};
|
||||
|
||||
use cosmwasm_std::{
|
||||
StdError,
|
||||
StdResult,
|
||||
Storage,
|
||||
};
|
||||
use cosmwasm_storage::{
|
||||
bucket,
|
||||
bucket_read,
|
||||
singleton,
|
||||
singleton_read,
|
||||
Bucket,
|
||||
ReadonlyBucket,
|
||||
ReadonlySingleton,
|
||||
Singleton,
|
||||
};
|
||||
|
||||
use wormhole::byte_utils::ByteUtils;
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
pub static CONFIG_KEY: &[u8] = b"config";
|
||||
pub static WRAPPED_ASSET_KEY: &[u8] = b"wrapped_asset";
|
||||
pub static WRAPPED_ASSET_ADDRESS_KEY: &[u8] = b"wrapped_asset_address";
|
||||
pub static BRIDGE_CONTRACTS_KEY: &[u8] = b"bridge_contracts";
|
||||
pub static TOKEN_ID_HASHES_KEY: &[u8] = b"token_id_hashes";
|
||||
pub static SPL_CACHE_KEY: &[u8] = b"spl_cache";
|
||||
|
||||
// Guardian set information
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct ConfigInfo {
|
||||
// governance contract details
|
||||
pub gov_chain: u16,
|
||||
pub gov_address: Vec<u8>,
|
||||
|
||||
pub wormhole_contract: HumanAddr,
|
||||
pub wrapped_asset_code_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct SplCacheItem {
|
||||
pub name: [u8; 32],
|
||||
pub symbol: [u8; 32],
|
||||
}
|
||||
|
||||
pub fn config(storage: &mut dyn Storage) -> Singleton<ConfigInfo> {
|
||||
singleton(storage, CONFIG_KEY)
|
||||
}
|
||||
|
||||
pub fn config_read(storage: &dyn Storage) -> ReadonlySingleton<ConfigInfo> {
|
||||
singleton_read(storage, CONFIG_KEY)
|
||||
}
|
||||
|
||||
pub fn bridge_contracts(storage: &mut dyn Storage) -> Bucket<Vec<u8>> {
|
||||
bucket(storage, BRIDGE_CONTRACTS_KEY)
|
||||
}
|
||||
|
||||
pub fn bridge_contracts_read(storage: &dyn Storage) -> ReadonlyBucket<Vec<u8>> {
|
||||
bucket_read(storage, BRIDGE_CONTRACTS_KEY)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset(storage: &mut dyn Storage) -> Bucket<HumanAddr> {
|
||||
bucket(storage, WRAPPED_ASSET_KEY)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_read(storage: &dyn Storage) -> ReadonlyBucket<HumanAddr> {
|
||||
bucket_read(storage, WRAPPED_ASSET_KEY)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_address(storage: &mut dyn Storage) -> Bucket<Vec<u8>> {
|
||||
bucket(storage, WRAPPED_ASSET_ADDRESS_KEY)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_address_read(storage: &dyn Storage) -> ReadonlyBucket<Vec<u8>> {
|
||||
bucket_read(storage, WRAPPED_ASSET_ADDRESS_KEY)
|
||||
}
|
||||
|
||||
pub fn spl_cache(storage: &mut dyn Storage) -> Bucket<SplCacheItem> {
|
||||
bucket(storage, SPL_CACHE_KEY)
|
||||
}
|
||||
|
||||
pub fn spl_cache_read(storage: &dyn Storage) -> ReadonlyBucket<SplCacheItem> {
|
||||
bucket_read(storage, SPL_CACHE_KEY)
|
||||
}
|
||||
|
||||
pub fn token_id_hashes(storage: &mut dyn Storage, chain: u16, address: [u8; 32]) -> Bucket<String> {
|
||||
Bucket::multilevel(
|
||||
storage,
|
||||
&[TOKEN_ID_HASHES_KEY, &chain.to_be_bytes(), &address],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn token_id_hashes_read(
|
||||
storage: &mut dyn Storage,
|
||||
chain: u16,
|
||||
address: [u8; 32],
|
||||
) -> ReadonlyBucket<String> {
|
||||
ReadonlyBucket::multilevel(
|
||||
storage,
|
||||
&[TOKEN_ID_HASHES_KEY, &chain.to_be_bytes(), &address],
|
||||
)
|
||||
}
|
||||
|
||||
pub struct Action;
|
||||
|
||||
impl Action {
|
||||
pub const TRANSFER: u8 = 1;
|
||||
}
|
||||
|
||||
// 0 u8 action
|
||||
// 1 [u8] payload
|
||||
pub struct TokenBridgeMessage {
|
||||
pub action: u8,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl TokenBridgeMessage {
|
||||
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
|
||||
let action = data.get_u8(0);
|
||||
let payload = &data[1..];
|
||||
|
||||
Ok(TokenBridgeMessage {
|
||||
action,
|
||||
payload: payload.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
[self.action.to_be_bytes().to_vec(), self.payload.clone()].concat()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[repr(transparent)]
|
||||
pub struct BoundedVec<T, const N: usize> {
|
||||
vec: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T, const N: usize> BoundedVec<T, N> {
|
||||
pub fn new(vec: Vec<T>) -> StdResult<Self> {
|
||||
if vec.len() > N {
|
||||
return Result::Err(StdError::GenericErr {
|
||||
msg: format!("vector length exceeds {}", N),
|
||||
});
|
||||
};
|
||||
Ok(Self { vec })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_vec(&self) -> Vec<T>
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
self.vec.clone()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize {
|
||||
self.vec.len()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.vec.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct TransferInfo {
|
||||
pub nft_address: [u8; 32],
|
||||
pub nft_chain: u16,
|
||||
pub symbol: [u8; 32],
|
||||
pub name: [u8; 32],
|
||||
pub token_id: [u8; 32],
|
||||
pub uri: BoundedVec<u8, 200>, // max 200 bytes due to Solana
|
||||
pub recipient: [u8; 32],
|
||||
pub recipient_chain: u16,
|
||||
}
|
||||
|
||||
impl TransferInfo {
|
||||
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
|
||||
let mut offset: usize = 0; // offset into data in bytes
|
||||
let nft_address = data.get_const_bytes::<32>(offset);
|
||||
offset += 32;
|
||||
let nft_chain = data.get_u16(offset);
|
||||
offset += 2;
|
||||
let symbol = data.get_const_bytes::<32>(offset);
|
||||
offset += 32;
|
||||
let name = data.get_const_bytes::<32>(offset);
|
||||
offset += 32;
|
||||
let token_id = data.get_const_bytes::<32>(offset);
|
||||
offset += 32;
|
||||
let uri_length: usize = data.get_u8(offset).into();
|
||||
offset += 1;
|
||||
let uri = data.get_bytes(offset, uri_length).to_vec();
|
||||
offset += uri_length;
|
||||
let recipient = data.get_const_bytes::<32>(offset);
|
||||
offset += 32;
|
||||
let recipient_chain = data.get_u16(offset);
|
||||
offset += 2;
|
||||
|
||||
if data.len() != offset {
|
||||
return Result::Err(StdError::GenericErr {
|
||||
msg: format!(
|
||||
"Invalid transfer length, expected {}, but got {}",
|
||||
offset,
|
||||
data.len()
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(TransferInfo {
|
||||
nft_address,
|
||||
nft_chain,
|
||||
symbol,
|
||||
name,
|
||||
token_id,
|
||||
uri: BoundedVec::new(uri.to_vec())?,
|
||||
recipient,
|
||||
recipient_chain,
|
||||
})
|
||||
}
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
[
|
||||
self.nft_address.to_vec(),
|
||||
self.nft_chain.to_be_bytes().to_vec(),
|
||||
self.symbol.to_vec(),
|
||||
self.name.to_vec(),
|
||||
self.token_id.to_vec(),
|
||||
vec![self.uri.len().try_into().unwrap()], // won't panic, because uri.len() is less than 200
|
||||
self.uri.to_vec(),
|
||||
self.recipient.to_vec(),
|
||||
self.recipient_chain.to_be_bytes().to_vec(),
|
||||
]
|
||||
.concat()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UpgradeContract {
|
||||
pub new_contract: u64,
|
||||
}
|
||||
|
||||
pub struct RegisterChain {
|
||||
pub chain_id: u16,
|
||||
pub chain_address: Vec<u8>,
|
||||
}
|
||||
|
||||
impl UpgradeContract {
|
||||
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
|
||||
let new_contract = data.get_u64(24);
|
||||
Ok(UpgradeContract { new_contract })
|
||||
}
|
||||
}
|
||||
|
||||
impl RegisterChain {
|
||||
pub fn deserialize(data: &[u8]) -> StdResult<Self> {
|
||||
let chain_id = data.get_u16(0);
|
||||
let chain_address = data[2..].to_vec();
|
||||
|
||||
Ok(RegisterChain {
|
||||
chain_id,
|
||||
chain_address,
|
||||
})
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
use bigint::U256;
|
||||
use cosmwasm_std::{
|
||||
StdError,
|
||||
StdResult,
|
||||
Storage,
|
||||
};
|
||||
|
||||
use sha3::{
|
||||
digest::{consts::U32, generic_array::GenericArray},
|
||||
Digest, Keccak256,
|
||||
};
|
||||
use wormhole::byte_utils::ByteUtils;
|
||||
|
||||
use crate::{
|
||||
state::{
|
||||
token_id_hashes,
|
||||
token_id_hashes_read,
|
||||
},
|
||||
CHAIN_ID,
|
||||
};
|
||||
|
||||
// NOTE: [External and internal token id conversion]
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// The CW721 NFT standard allows token ids to be arbitrarily long (utf8)
|
||||
// strings, while the token_ids in VAA payloads are always 32 bytes (and not
|
||||
// necessarily valid utf8).
|
||||
//
|
||||
// We call a token id that's in string format an "internal id", and a token id
|
||||
// that's in 32 byte format an "external id". Note that whether a token id is in
|
||||
// internal format or external format doesn't imply which chain the token id
|
||||
// originates from. We can have a terra (native) token id in both internal and
|
||||
// external formats, and likewise we can have an ethereum token in in both
|
||||
// internal and external formats.
|
||||
//
|
||||
// To support seamless transfers through the bridge, we need a way to have a
|
||||
// 1-to-1 mapping from internal ids to external ids.
|
||||
// When a foreign (such as ethereum or solana) token id first comes through, we
|
||||
// simply render it into a string by formatting it as a decimal number. Then,
|
||||
// when we want to transfer such a token back through the bridge, we simply
|
||||
// parse the string back into a u256 (32 byte) number.
|
||||
//
|
||||
// When a native token id first leaves through the bridge, we turn its id into a
|
||||
// 32 byte hash (keccak256). This hash is the external id. We store a mapping
|
||||
//
|
||||
// (chain_id, nft_address, keccak256(internal_id)) => internal_id
|
||||
//
|
||||
// so that we can turn it back into an internal id when it comes back through
|
||||
// the bridge. When the token is sent back, we could choose to delete the hash
|
||||
// from the store, but we do not. This way, external token verifiers will be
|
||||
// able to verify NFT origins even for NFTs that have been transferred back.
|
||||
//
|
||||
// If two token ids within the same contract have the same keccak256 hash, then
|
||||
// it's possible to lose tokens, but this is very unlikely.
|
||||
|
||||
pub fn from_external_token_id(
|
||||
storage: &mut dyn Storage,
|
||||
nft_chain: u16,
|
||||
nft_address: &[u8; 32],
|
||||
token_id_external: &[u8; 32],
|
||||
) -> StdResult<String> {
|
||||
if nft_chain == CHAIN_ID {
|
||||
token_id_hashes_read(storage, nft_chain, *nft_address).load(token_id_external)
|
||||
} else {
|
||||
Ok(format!("{}", U256::from_big_endian(token_id_external)))
|
||||
}
|
||||
}
|
||||
|
||||
fn hash(token_id: &str) -> GenericArray<u8, U32> {
|
||||
let mut hasher = Keccak256::new();
|
||||
hasher.update(token_id);
|
||||
hasher.finalize()
|
||||
}
|
||||
|
||||
pub fn to_external_token_id(
|
||||
storage: &mut dyn Storage,
|
||||
nft_chain: u16,
|
||||
nft_address: &[u8; 32],
|
||||
token_id_internal: String,
|
||||
) -> StdResult<[u8; 32]> {
|
||||
if nft_chain == CHAIN_ID {
|
||||
let hash = hash(&token_id_internal);
|
||||
token_id_hashes(storage, nft_chain, *nft_address).save(&hash, &token_id_internal)?;
|
||||
Ok(hash.as_slice().get_const_bytes(0))
|
||||
} else {
|
||||
let mut bytes = [0; 32];
|
||||
U256::from_dec_str(&token_id_internal)
|
||||
.map_err(|_| {
|
||||
StdError::generic_err(format!(
|
||||
"{} could not be parsed as a decimal number",
|
||||
token_id_internal
|
||||
))
|
||||
})?
|
||||
.to_big_endian(&mut bytes);
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
[package]
|
||||
name = "token-bridge-terra"
|
||||
name = "token-bridge-terra-2"
|
||||
version = "0.1.0"
|
||||
authors = ["Yuriy Savchenko <yuriy.savchenko@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
@ -14,16 +14,16 @@ backtraces = ["cosmwasm-std/backtraces"]
|
|||
library = []
|
||||
|
||||
[dependencies]
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
cosmwasm-storage = { version = "0.16.0" }
|
||||
schemars = "0.8.1"
|
||||
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
|
||||
cw20 = "0.8.0"
|
||||
cw20-base = { version = "0.8.0", features = ["library"] }
|
||||
cw20-wrapped = { path = "../cw20-wrapped", features = ["library"] }
|
||||
terraswap = "2.4.0"
|
||||
wormhole-bridge-terra = { path = "../wormhole", features = ["library"] }
|
||||
thiserror = { version = "1.0.20" }
|
||||
cosmwasm-std = { version = "1.0.0" }
|
||||
cosmwasm-storage = { version = "1.0.0" }
|
||||
schemars = "0.8.8"
|
||||
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
|
||||
cw20 = "0.13.2"
|
||||
cw20-base = { version = "0.13.2", features = ["library"] }
|
||||
cw20-wrapped-2 = { path = "../cw20-wrapped", features = ["library"] }
|
||||
terraswap = "2.6.1"
|
||||
wormhole-bridge-terra-2 = { path = "../wormhole", features = ["library"] }
|
||||
thiserror = { version = "1.0.31" }
|
||||
k256 = { version = "0.9.4", default-features = false, features = ["ecdsa"] }
|
||||
sha3 = { version = "0.9.1", default-features = false }
|
||||
generic-array = { version = "0.14.4" }
|
||||
|
|
|
@ -6,17 +6,13 @@ use cw20_base::msg::{
|
|||
ExecuteMsg as TokenMsg,
|
||||
QueryMsg as TokenQuery,
|
||||
};
|
||||
use cw20_wrapped::msg::{
|
||||
use cw20_wrapped_2::msg::{
|
||||
ExecuteMsg as WrappedMsg,
|
||||
InitHook,
|
||||
InstantiateMsg as WrappedInit,
|
||||
QueryMsg as WrappedQuery,
|
||||
WrappedAssetInfoResponse,
|
||||
};
|
||||
use sha3::{
|
||||
Digest,
|
||||
Keccak256,
|
||||
};
|
||||
use std::{
|
||||
cmp::{
|
||||
max,
|
||||
|
@ -32,6 +28,7 @@ use terraswap::asset::{
|
|||
use wormhole::{
|
||||
byte_utils::{
|
||||
extend_address_to_32,
|
||||
extend_address_to_32_array,
|
||||
extend_string_to_32,
|
||||
get_string_from_32,
|
||||
ByteUtils,
|
||||
|
@ -49,14 +46,15 @@ use wormhole::{
|
|||
},
|
||||
};
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use cosmwasm_std::entry_point;
|
||||
|
||||
use cosmwasm_std::{
|
||||
coin,
|
||||
entry_point,
|
||||
to_binary,
|
||||
BankMsg,
|
||||
Binary,
|
||||
CanonicalAddr,
|
||||
Coin,
|
||||
CosmosMsg,
|
||||
Deps,
|
||||
DepsMut,
|
||||
|
@ -77,6 +75,7 @@ use cosmwasm_std::{
|
|||
use crate::{
|
||||
msg::{
|
||||
ExecuteMsg,
|
||||
ExternalIdResponse,
|
||||
InstantiateMsg,
|
||||
MigrateMsg,
|
||||
QueryMsg,
|
||||
|
@ -89,11 +88,11 @@ use crate::{
|
|||
bridge_deposit,
|
||||
config,
|
||||
config_read,
|
||||
is_wrapped_asset,
|
||||
is_wrapped_asset_read,
|
||||
receive_native,
|
||||
send_native,
|
||||
wrapped_asset,
|
||||
wrapped_asset_address,
|
||||
wrapped_asset_address_read,
|
||||
wrapped_asset_read,
|
||||
wrapped_asset_seq,
|
||||
wrapped_asset_seq_read,
|
||||
|
@ -108,15 +107,17 @@ use crate::{
|
|||
TransferWithPayloadInfo,
|
||||
UpgradeContract,
|
||||
},
|
||||
token_address::{
|
||||
ContractId,
|
||||
ExternalTokenId,
|
||||
TokenId,
|
||||
WrappedCW20,
|
||||
},
|
||||
CHAIN_ID,
|
||||
};
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
// Chain ID of Terra
|
||||
const CHAIN_ID: u16 = 3;
|
||||
|
||||
const WRAPPED_ASSET_UPDATING: &str = "updating";
|
||||
|
||||
pub enum TransferType<A> {
|
||||
WithoutPayload,
|
||||
WithPayload { payload: A },
|
||||
|
@ -180,7 +181,7 @@ pub fn reply(deps: DepsMut, env: Env, _msg: Reply) -> StdResult<Response> {
|
|||
// Fetch CW20 Balance post-transfer.
|
||||
let new_balance: BalanceResponse =
|
||||
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
|
||||
contract_addr: state.token_address.clone(),
|
||||
contract_addr: state.token_address.to_string(),
|
||||
msg: to_binary(&TokenQuery::Balance {
|
||||
address: env.contract.address.to_string(),
|
||||
})?,
|
||||
|
@ -225,26 +226,13 @@ pub fn reply(deps: DepsMut, env: Env, _msg: Reply) -> StdResult<Response> {
|
|||
})?,
|
||||
});
|
||||
|
||||
send_native(deps.storage, &state.token_canonical, real_amount)?;
|
||||
let external_id = ExternalTokenId::from_native_cw20(&state.token_address)?;
|
||||
send_native(deps.storage, &external_id, real_amount)?;
|
||||
Ok(Response::default()
|
||||
.add_message(message)
|
||||
.add_attribute("action", "reply_handler"))
|
||||
}
|
||||
|
||||
pub fn coins_after_tax(deps: DepsMut, coins: Vec<Coin>) -> StdResult<Vec<Coin>> {
|
||||
let mut res = vec![];
|
||||
for coin in coins {
|
||||
let asset = Asset {
|
||||
amount: coin.amount.clone(),
|
||||
info: AssetInfo::NativeToken {
|
||||
denom: coin.denom.clone(),
|
||||
},
|
||||
};
|
||||
res.push(asset.deduct_tax(&deps.querier)?);
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn parse_vaa(deps: Deps, block_time: u64, data: &Binary) -> StdResult<ParsedVAA> {
|
||||
let cfg = config_read(deps.storage).load()?;
|
||||
let vaa: ParsedVAA = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
|
||||
|
@ -260,9 +248,10 @@ fn parse_vaa(deps: Deps, block_time: u64, data: &Binary) -> StdResult<ParsedVAA>
|
|||
#[cfg_attr(not(feature = "library"), entry_point)]
|
||||
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {
|
||||
match msg {
|
||||
ExecuteMsg::RegisterAssetHook { asset_id } => {
|
||||
handle_register_asset(deps, env, info, &asset_id.as_slice())
|
||||
}
|
||||
ExecuteMsg::RegisterAssetHook {
|
||||
chain,
|
||||
token_address,
|
||||
} => handle_register_asset(deps, env, info, chain, token_address),
|
||||
ExecuteMsg::InitiateTransfer {
|
||||
asset,
|
||||
recipient_chain,
|
||||
|
@ -275,7 +264,7 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> S
|
|||
info,
|
||||
asset,
|
||||
recipient_chain,
|
||||
recipient.into(),
|
||||
recipient.to_array()?,
|
||||
fee,
|
||||
TransferType::WithoutPayload,
|
||||
nonce,
|
||||
|
@ -293,7 +282,7 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> S
|
|||
info,
|
||||
asset,
|
||||
recipient_chain,
|
||||
recipient.into(),
|
||||
recipient.to_array()?,
|
||||
fee,
|
||||
TransferType::WithPayload {
|
||||
payload: payload.into(),
|
||||
|
@ -348,7 +337,7 @@ fn withdraw_tokens(
|
|||
)?;
|
||||
messages.push(CosmosMsg::Bank(BankMsg::Send {
|
||||
to_address: info.sender.to_string(),
|
||||
amount: coins_after_tax(deps, vec![coin(deposited_amount, &denom)])?,
|
||||
amount: vec![coin(deposited_amount, &denom)],
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -362,23 +351,41 @@ fn handle_register_asset(
|
|||
deps: DepsMut,
|
||||
_env: Env,
|
||||
info: MessageInfo,
|
||||
asset_id: &[u8],
|
||||
chain: u16,
|
||||
token_address: ExternalTokenId,
|
||||
) -> StdResult<Response> {
|
||||
let mut bucket = wrapped_asset(deps.storage);
|
||||
let result = bucket.load(asset_id);
|
||||
let result = result.map_err(|_| ContractError::RegistrationForbidden.std())?;
|
||||
if result != HumanAddr::from(WRAPPED_ASSET_UPDATING) {
|
||||
// We need to ensure that this registration request was initiated by the
|
||||
// token bridge contract. We do this by checking that the wrapped asset
|
||||
// already has an associated sequence number, but no address entry yet.
|
||||
// This is a necessary and sufficient condition, because having the sequence
|
||||
// number means that [`handle_attest_meta`] has been called, and not having
|
||||
// an address entry yet means precisely that the callback hasn't finished
|
||||
// yet.
|
||||
|
||||
let _ = wrapped_asset_seq_read(deps.storage, chain)
|
||||
.load(&token_address.serialize())
|
||||
.map_err(|_| ContractError::RegistrationForbidden.std())?;
|
||||
|
||||
let mut bucket = wrapped_asset(deps.storage, chain);
|
||||
let result = bucket.load(&token_address.serialize()).ok();
|
||||
if let Some(_) = result {
|
||||
return ContractError::AssetAlreadyRegistered.std_err();
|
||||
}
|
||||
|
||||
bucket.save(asset_id, &info.sender.to_string())?;
|
||||
bucket.save(
|
||||
&token_address.serialize(),
|
||||
&WrappedCW20 {
|
||||
human_address: info.sender.clone(),
|
||||
},
|
||||
)?;
|
||||
|
||||
let contract_address: CanonicalAddr = deps.api.addr_canonicalize(&info.sender.as_str())?;
|
||||
wrapped_asset_address(deps.storage).save(contract_address.as_slice(), &asset_id.to_vec())?;
|
||||
is_wrapped_asset(deps.storage).save(contract_address.as_slice(), &())?;
|
||||
|
||||
Ok(Response::new()
|
||||
.add_attribute("action", "register_asset")
|
||||
.add_attribute("asset_id", format!("{:?}", asset_id))
|
||||
.add_attribute("token_chain", format!("{:?}", chain))
|
||||
.add_attribute("token_address", format!("{:?}", token_address))
|
||||
.add_attribute("contract_addr", info.sender))
|
||||
}
|
||||
|
||||
|
@ -400,26 +407,44 @@ fn handle_attest_meta(
|
|||
return Err(StdError::generic_err("invalid emitter"));
|
||||
}
|
||||
|
||||
if CHAIN_ID == meta.token_chain {
|
||||
return Err(StdError::generic_err(
|
||||
"this asset is native to this chain and should not be attested",
|
||||
));
|
||||
}
|
||||
let token_id = meta
|
||||
.token_address
|
||||
.to_token_id(deps.storage, emitter_chain)?;
|
||||
|
||||
let token_address: [u8; 32] = match token_id {
|
||||
TokenId::Bank { denom } => Err(StdError::generic_err(format!(
|
||||
"{} is native to this chain and should not be attested",
|
||||
denom
|
||||
))),
|
||||
TokenId::Contract(ContractId::NativeCW20 { contract_address }) => {
|
||||
Err(StdError::generic_err(format!(
|
||||
"Contract {} is native to this chain and should not be attested",
|
||||
contract_address
|
||||
)))
|
||||
}
|
||||
TokenId::Contract(ContractId::ForeignToken {
|
||||
chain_id: _,
|
||||
foreign_address,
|
||||
}) => Ok(foreign_address),
|
||||
}?;
|
||||
|
||||
let cfg = config_read(deps.storage).load()?;
|
||||
let asset_id = build_asset_id(meta.token_chain, &meta.token_address.as_slice());
|
||||
|
||||
// If a CW20 wrapped already exists and this message has a newer sequence ID
|
||||
// we allow updating the metadata. If not, we create a brand new token.
|
||||
let message = if let Ok(contract) = wrapped_asset_read(deps.storage).load(&asset_id) {
|
||||
let message = if let Ok(contract) =
|
||||
wrapped_asset_read(deps.storage, meta.token_chain).load(token_address.as_slice())
|
||||
{
|
||||
// Prevent anyone from re-attesting with old VAAs.
|
||||
if sequence <= wrapped_asset_seq_read(deps.storage).load(&asset_id)? {
|
||||
if sequence
|
||||
<= wrapped_asset_seq_read(deps.storage, meta.token_chain)
|
||||
.load(token_address.as_slice())?
|
||||
{
|
||||
return Err(StdError::generic_err(
|
||||
"this asset has already been attested",
|
||||
));
|
||||
}
|
||||
CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract,
|
||||
contract_addr: contract.into_string(),
|
||||
msg: to_binary(&WrappedMsg::UpdateMetadata {
|
||||
name: get_string_from_32(&meta.name),
|
||||
symbol: get_string_from_32(&meta.symbol),
|
||||
|
@ -427,7 +452,6 @@ fn handle_attest_meta(
|
|||
funds: vec![],
|
||||
})
|
||||
} else {
|
||||
wrapped_asset(deps.storage).save(&asset_id, &HumanAddr::from(WRAPPED_ASSET_UPDATING))?;
|
||||
CosmosMsg::Wasm(WasmMsg::Instantiate {
|
||||
admin: Some(env.contract.address.clone().into_string()),
|
||||
code_id: cfg.wrapped_asset_code_id,
|
||||
|
@ -435,21 +459,22 @@ fn handle_attest_meta(
|
|||
name: get_string_from_32(&meta.name),
|
||||
symbol: get_string_from_32(&meta.symbol),
|
||||
asset_chain: meta.token_chain,
|
||||
asset_address: meta.token_address.to_vec().into(),
|
||||
asset_address: token_address.into(),
|
||||
decimals: min(meta.decimals, 8u8),
|
||||
mint: None,
|
||||
init_hook: Some(InitHook {
|
||||
contract_addr: env.contract.address.to_string(),
|
||||
msg: to_binary(&ExecuteMsg::RegisterAssetHook {
|
||||
asset_id: asset_id.to_vec().into(),
|
||||
chain: meta.token_chain,
|
||||
token_address: meta.token_address.clone(),
|
||||
})?,
|
||||
}),
|
||||
})?,
|
||||
funds: vec![],
|
||||
label: String::new(),
|
||||
label: "Wormhole Wrapped CW20".to_string(),
|
||||
})
|
||||
};
|
||||
wrapped_asset_seq(deps.storage).save(&asset_id, &sequence)?;
|
||||
wrapped_asset_seq(deps.storage, meta.token_chain).save(&token_address, &sequence)?;
|
||||
Ok(Response::new().add_message(message))
|
||||
}
|
||||
|
||||
|
@ -484,12 +509,16 @@ fn handle_create_asset_meta_token(
|
|||
msg: to_binary(&TokenQuery::TokenInfo {})?,
|
||||
});
|
||||
|
||||
let asset_canonical = deps.api.addr_canonicalize(&asset_address)?;
|
||||
let asset_human = deps.api.addr_validate(&asset_address)?;
|
||||
let token_id = TokenId::Contract(ContractId::NativeCW20 {
|
||||
contract_address: asset_human,
|
||||
});
|
||||
let external_id = token_id.store(deps.storage)?;
|
||||
let token_info: TokenInfoResponse = deps.querier.query(&request)?;
|
||||
|
||||
let meta: AssetMeta = AssetMeta {
|
||||
token_chain: CHAIN_ID,
|
||||
token_address: extend_address_to_32(&asset_canonical),
|
||||
token_address: external_id,
|
||||
decimals: token_info.decimals,
|
||||
symbol: extend_string_to_32(&token_info.symbol),
|
||||
name: extend_string_to_32(&token_info.name),
|
||||
|
@ -508,7 +537,7 @@ fn handle_create_asset_meta_token(
|
|||
nonce,
|
||||
})?,
|
||||
// forward coins sent to this message
|
||||
funds: coins_after_tax(deps, info.funds.clone())?,
|
||||
funds: info.funds.clone(),
|
||||
}))
|
||||
.add_attribute("meta.token_chain", CHAIN_ID.to_string())
|
||||
.add_attribute("meta.token", asset_address)
|
||||
|
@ -524,12 +553,14 @@ fn handle_create_asset_meta_native_token(
|
|||
nonce: u32,
|
||||
) -> StdResult<Response> {
|
||||
let cfg = config_read(deps.storage).load()?;
|
||||
let mut asset_id = extend_address_to_32(&build_native_id(&denom).into());
|
||||
asset_id[0] = 1;
|
||||
|
||||
let symbol = format_native_denom_symbol(&denom);
|
||||
let token_id = TokenId::Bank { denom };
|
||||
let external_id = token_id.store(deps.storage)?;
|
||||
|
||||
let meta: AssetMeta = AssetMeta {
|
||||
token_chain: CHAIN_ID,
|
||||
token_address: asset_id.clone(),
|
||||
token_address: external_id.clone(),
|
||||
decimals: 6,
|
||||
symbol: extend_string_to_32(&symbol),
|
||||
name: extend_string_to_32(&symbol),
|
||||
|
@ -546,105 +577,115 @@ fn handle_create_asset_meta_native_token(
|
|||
nonce,
|
||||
})?,
|
||||
// forward coins sent to this message
|
||||
funds: coins_after_tax(deps, info.funds.clone())?,
|
||||
funds: info.funds.clone(),
|
||||
}))
|
||||
.add_attribute("meta.token_chain", CHAIN_ID.to_string())
|
||||
.add_attribute("meta.symbol", symbol)
|
||||
.add_attribute("meta.asset_id", hex::encode(asset_id))
|
||||
.add_attribute("meta.asset_id", hex::encode(external_id.serialize()))
|
||||
.add_attribute("meta.nonce", nonce.to_string())
|
||||
.add_attribute("meta.block_time", env.block.time.seconds().to_string()))
|
||||
}
|
||||
|
||||
fn handle_complete_transfer_with_payload(
|
||||
deps: DepsMut,
|
||||
mut deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
data: &Binary,
|
||||
relayer_address: &HumanAddr,
|
||||
) -> StdResult<Response> {
|
||||
let state = config_read(deps.storage).load()?;
|
||||
let (vaa, payload) = parse_and_archive_vaa(deps.branch(), env.clone(), data)?;
|
||||
|
||||
let vaa = parse_vaa(deps.as_ref(), env.block.time.seconds(), data)?;
|
||||
let data = vaa.payload;
|
||||
|
||||
if vaa_archive_check(deps.storage, vaa.hash.as_slice()) {
|
||||
return ContractError::VaaAlreadyExecuted.std_err();
|
||||
}
|
||||
vaa_archive_add(deps.storage, vaa.hash.as_slice())?;
|
||||
|
||||
// check if vaa is from governance
|
||||
if is_governance_emitter(&state, vaa.emitter_chain, &vaa.emitter_address) {
|
||||
return ContractError::InvalidVAAAction.std_err();
|
||||
}
|
||||
|
||||
let message = TokenBridgeMessage::deserialize(&data)?;
|
||||
|
||||
match message.action {
|
||||
Action::TRANSFER_WITH_PAYLOAD => handle_complete_transfer(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
vaa.emitter_chain,
|
||||
vaa.emitter_address,
|
||||
TransferType::WithPayload { payload: () },
|
||||
&message.payload,
|
||||
relayer_address,
|
||||
),
|
||||
_ => ContractError::InvalidVAAAction.std_err(),
|
||||
}
|
||||
}
|
||||
|
||||
fn submit_vaa(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
data: &Binary,
|
||||
) -> StdResult<Response> {
|
||||
let state = config_read(deps.storage).load()?;
|
||||
|
||||
let vaa = parse_vaa(deps.as_ref(), env.block.time.seconds(), data)?;
|
||||
let data = vaa.payload;
|
||||
|
||||
if vaa_archive_check(deps.storage, vaa.hash.as_slice()) {
|
||||
return ContractError::VaaAlreadyExecuted.std_err();
|
||||
}
|
||||
vaa_archive_add(deps.storage, vaa.hash.as_slice())?;
|
||||
|
||||
// check if vaa is from governance
|
||||
if is_governance_emitter(&state, vaa.emitter_chain, &vaa.emitter_address) {
|
||||
return handle_governance_payload(deps, env, &data);
|
||||
}
|
||||
|
||||
let message = TokenBridgeMessage::deserialize(&data)?;
|
||||
|
||||
match message.action {
|
||||
Action::TRANSFER => {
|
||||
let sender = info.sender.to_string();
|
||||
handle_complete_transfer(
|
||||
if let Either::Right(message) = payload {
|
||||
match message.action {
|
||||
Action::TRANSFER_WITH_PAYLOAD => handle_complete_transfer(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
vaa.emitter_chain,
|
||||
vaa.emitter_address,
|
||||
TransferType::WithoutPayload,
|
||||
TransferType::WithPayload { payload: () },
|
||||
&message.payload,
|
||||
&sender,
|
||||
)
|
||||
relayer_address,
|
||||
),
|
||||
_ => ContractError::InvalidVAAAction.std_err(),
|
||||
}
|
||||
Action::ATTEST_META => handle_attest_meta(
|
||||
deps,
|
||||
env,
|
||||
vaa.emitter_chain,
|
||||
vaa.emitter_address,
|
||||
vaa.sequence,
|
||||
&message.payload,
|
||||
),
|
||||
_ => ContractError::InvalidVAAAction.std_err(),
|
||||
} else {
|
||||
return ContractError::InvalidVAAAction.std_err();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_governance_payload(deps: DepsMut, env: Env, data: &Vec<u8>) -> StdResult<Response> {
|
||||
let gov_packet = GovernancePacket::deserialize(&data)?;
|
||||
enum Either<A, B> {
|
||||
Left(A),
|
||||
Right(B),
|
||||
}
|
||||
|
||||
fn parse_and_archive_vaa(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
data: &Binary,
|
||||
) -> StdResult<(ParsedVAA, Either<GovernancePacket, TokenBridgeMessage>)> {
|
||||
let state = config_read(deps.storage).load()?;
|
||||
|
||||
let vaa = parse_vaa(deps.as_ref(), env.block.time.seconds(), data)?;
|
||||
|
||||
if vaa_archive_check(deps.storage, vaa.hash.as_slice()) {
|
||||
return ContractError::VaaAlreadyExecuted.std_err();
|
||||
}
|
||||
vaa_archive_add(deps.storage, vaa.hash.as_slice())?;
|
||||
|
||||
// check if vaa is from governance
|
||||
if is_governance_emitter(&state, vaa.emitter_chain, &vaa.emitter_address) {
|
||||
let gov_packet = GovernancePacket::deserialize(&vaa.payload)?;
|
||||
return Ok((vaa, Either::Left(gov_packet)));
|
||||
}
|
||||
|
||||
let message = TokenBridgeMessage::deserialize(&vaa.payload)?;
|
||||
return Ok((vaa, Either::Right(message)));
|
||||
}
|
||||
|
||||
fn submit_vaa(
|
||||
mut deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
data: &Binary,
|
||||
) -> StdResult<Response> {
|
||||
let (vaa, payload) = parse_and_archive_vaa(deps.branch(), env.clone(), data)?;
|
||||
match payload {
|
||||
Either::Left(governance_packet) => {
|
||||
return handle_governance_payload(deps, env, &governance_packet)
|
||||
}
|
||||
Either::Right(message) => match message.action {
|
||||
Action::TRANSFER => {
|
||||
let sender = info.sender.to_string();
|
||||
handle_complete_transfer(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
vaa.emitter_chain,
|
||||
vaa.emitter_address,
|
||||
TransferType::WithoutPayload,
|
||||
&message.payload,
|
||||
&sender,
|
||||
)
|
||||
}
|
||||
Action::ATTEST_META => handle_attest_meta(
|
||||
deps,
|
||||
env,
|
||||
vaa.emitter_chain,
|
||||
vaa.emitter_address,
|
||||
vaa.sequence,
|
||||
&message.payload,
|
||||
),
|
||||
_ => ContractError::InvalidVAAAction.std_err(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_governance_payload(
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
gov_packet: &GovernancePacket,
|
||||
) -> StdResult<Response> {
|
||||
let module = get_string_from_32(&gov_packet.module);
|
||||
|
||||
if module != "TokenBridge" {
|
||||
|
@ -708,23 +749,28 @@ fn handle_complete_transfer(
|
|||
relayer_address: &HumanAddr,
|
||||
) -> StdResult<Response> {
|
||||
let transfer_info = TransferInfo::deserialize(&data)?;
|
||||
match transfer_info.token_address.as_slice()[0] {
|
||||
1 => handle_complete_transfer_token_native(
|
||||
let token_id = transfer_info
|
||||
.token_address
|
||||
.to_token_id(deps.storage, transfer_info.token_chain)?;
|
||||
match token_id {
|
||||
TokenId::Bank { denom } => handle_complete_transfer_token_native(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
emitter_chain,
|
||||
emitter_address,
|
||||
denom,
|
||||
transfer_type,
|
||||
data,
|
||||
relayer_address,
|
||||
),
|
||||
_ => handle_complete_transfer_token(
|
||||
TokenId::Contract(contract) => handle_complete_transfer_token(
|
||||
deps,
|
||||
env,
|
||||
info,
|
||||
emitter_chain,
|
||||
emitter_address,
|
||||
contract,
|
||||
transfer_type,
|
||||
data,
|
||||
relayer_address,
|
||||
|
@ -738,6 +784,7 @@ fn handle_complete_transfer_token(
|
|||
info: MessageInfo,
|
||||
emitter_chain: u16,
|
||||
emitter_address: Vec<u8>,
|
||||
token_contract: ContractId,
|
||||
transfer_type: TransferType<()>,
|
||||
data: &Vec<u8>,
|
||||
relayer_address: &HumanAddr,
|
||||
|
@ -763,7 +810,6 @@ fn handle_complete_transfer_token(
|
|||
));
|
||||
}
|
||||
|
||||
let token_chain = transfer_info.token_chain;
|
||||
let target_address = (&transfer_info.recipient.as_slice()).get_address(0);
|
||||
let recipient = deps.api.addr_humanize(&target_address)?;
|
||||
|
||||
|
@ -785,16 +831,20 @@ fn handle_complete_transfer_token(
|
|||
return ContractError::AmountTooHigh.std_err();
|
||||
}
|
||||
|
||||
if token_chain != CHAIN_ID {
|
||||
let asset_address = transfer_info.token_address;
|
||||
let asset_id = build_asset_id(token_chain, &asset_address);
|
||||
let external_id = ExternalTokenId::from_token_id(&TokenId::Contract(token_contract.clone()))?;
|
||||
|
||||
// Check if this asset is already deployed
|
||||
let contract_addr = wrapped_asset_read(deps.storage).load(&asset_id).ok();
|
||||
match token_contract {
|
||||
ContractId::ForeignToken {
|
||||
chain_id,
|
||||
foreign_address,
|
||||
} => {
|
||||
// Check if this asset is already deployed
|
||||
let contract_addr = wrapped_asset_read(deps.storage, chain_id).load(&foreign_address).
|
||||
or_else(|_| Err(StdError::generic_err("Wrapped asset not deployed. To deploy, invoke CreateWrapped with the associated AssetMeta")))?;
|
||||
|
||||
let contract_addr = contract_addr.into_string();
|
||||
|
||||
return if let Some(contract_addr) = contract_addr {
|
||||
// Asset already deployed, just mint
|
||||
|
||||
let mut messages = vec![CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_addr.clone(),
|
||||
msg: to_binary(&WrappedMsg::Mint {
|
||||
|
@ -822,67 +872,63 @@ fn handle_complete_transfer_token(
|
|||
.add_attribute("amount", amount.to_string())
|
||||
.add_attribute("relayer", relayer_address)
|
||||
.add_attribute("fee", fee.to_string()))
|
||||
} else {
|
||||
Err(StdError::generic_err("Wrapped asset not deployed. To deploy, invoke CreateWrapped with the associated AssetMeta"))
|
||||
};
|
||||
} else {
|
||||
let token_address = transfer_info.token_address.as_slice().get_address(0);
|
||||
}
|
||||
ContractId::NativeCW20 { contract_address } => {
|
||||
// note -- here the amount is the amount the recipient will receive;
|
||||
// amount + fee is the total sent
|
||||
receive_native(deps.storage, &external_id, Uint128::new(amount + fee))?;
|
||||
|
||||
let contract_addr = deps.api.addr_humanize(&token_address)?;
|
||||
// undo normalization to 8 decimals
|
||||
let token_info: TokenInfoResponse =
|
||||
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
|
||||
contract_addr: contract_address.to_string(),
|
||||
msg: to_binary(&TokenQuery::TokenInfo {})?,
|
||||
}))?;
|
||||
|
||||
// note -- here the amount is the amount the recipient will receive;
|
||||
// amount + fee is the total sent
|
||||
receive_native(deps.storage, &token_address, Uint128::new(amount + fee))?;
|
||||
let decimals = token_info.decimals;
|
||||
let multiplier = 10u128.pow((max(decimals, 8u8) - 8u8) as u32);
|
||||
amount = amount.checked_mul(multiplier).unwrap();
|
||||
fee = fee.checked_mul(multiplier).unwrap();
|
||||
|
||||
// undo normalization to 8 decimals
|
||||
let token_info: TokenInfoResponse =
|
||||
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
|
||||
contract_addr: contract_addr.to_string(),
|
||||
msg: to_binary(&TokenQuery::TokenInfo {})?,
|
||||
}))?;
|
||||
|
||||
let decimals = token_info.decimals;
|
||||
let multiplier = 10u128.pow((max(decimals, 8u8) - 8u8) as u32);
|
||||
amount = amount.checked_mul(multiplier).unwrap();
|
||||
fee = fee.checked_mul(multiplier).unwrap();
|
||||
|
||||
let mut messages = vec![CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_addr.to_string(),
|
||||
msg: to_binary(&TokenMsg::Transfer {
|
||||
recipient: recipient.to_string(),
|
||||
amount: Uint128::from(amount),
|
||||
})?,
|
||||
funds: vec![],
|
||||
})];
|
||||
|
||||
if fee != 0 {
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_addr.to_string(),
|
||||
let mut messages = vec![CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_address.to_string(),
|
||||
msg: to_binary(&TokenMsg::Transfer {
|
||||
recipient: relayer_address.to_string(),
|
||||
amount: Uint128::from(fee),
|
||||
recipient: recipient.to_string(),
|
||||
amount: Uint128::from(amount),
|
||||
})?,
|
||||
funds: vec![],
|
||||
}))
|
||||
}
|
||||
})];
|
||||
|
||||
Ok(Response::new()
|
||||
.add_messages(messages)
|
||||
.add_attribute("action", "complete_transfer_native")
|
||||
.add_attribute("recipient", recipient)
|
||||
.add_attribute("contract", contract_addr)
|
||||
.add_attribute("amount", amount.to_string())
|
||||
.add_attribute("relayer", relayer_address)
|
||||
.add_attribute("fee", fee.to_string()))
|
||||
if fee != 0 {
|
||||
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
|
||||
contract_addr: contract_address.to_string(),
|
||||
msg: to_binary(&TokenMsg::Transfer {
|
||||
recipient: relayer_address.to_string(),
|
||||
amount: Uint128::from(fee),
|
||||
})?,
|
||||
funds: vec![],
|
||||
}))
|
||||
}
|
||||
|
||||
Ok(Response::new()
|
||||
.add_messages(messages)
|
||||
.add_attribute("action", "complete_transfer_native")
|
||||
.add_attribute("recipient", recipient)
|
||||
.add_attribute("contract", contract_address)
|
||||
.add_attribute("amount", amount.to_string())
|
||||
.add_attribute("relayer", relayer_address)
|
||||
.add_attribute("fee", fee.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_complete_transfer_token_native(
|
||||
mut deps: DepsMut,
|
||||
deps: DepsMut,
|
||||
_env: Env,
|
||||
info: MessageInfo,
|
||||
emitter_chain: u16,
|
||||
emitter_address: Vec<u8>,
|
||||
denom: String,
|
||||
transfer_type: TransferType<()>,
|
||||
data: &Vec<u8>,
|
||||
relayer_address: &HumanAddr,
|
||||
|
@ -929,29 +975,18 @@ fn handle_complete_transfer_token_native(
|
|||
return ContractError::AmountTooHigh.std_err();
|
||||
}
|
||||
|
||||
// Wipe the native byte marker and extract the serialized denom.
|
||||
let mut token_address = transfer_info.token_address.clone();
|
||||
let token_address = token_address.as_mut_slice();
|
||||
token_address[0] = 0;
|
||||
|
||||
let mut denom = token_address.to_vec();
|
||||
denom.retain(|&c| c != 0);
|
||||
let denom = String::from_utf8(denom).unwrap();
|
||||
|
||||
// note -- here the amount is the amount the recipient will receive;
|
||||
// amount + fee is the total sent
|
||||
let token_address = (&*token_address).get_address(0);
|
||||
receive_native(deps.storage, &token_address, Uint128::new(amount + fee))?;
|
||||
let external_address = ExternalTokenId::from_bank_token(&denom)?;
|
||||
receive_native(deps.storage, &external_address, Uint128::new(amount + fee))?;
|
||||
|
||||
let mut messages = vec![CosmosMsg::Bank(BankMsg::Send {
|
||||
to_address: recipient.to_string(),
|
||||
amount: coins_after_tax(deps.branch(), vec![coin(amount, &denom)])?,
|
||||
amount: vec![coin(amount, &denom)],
|
||||
})];
|
||||
|
||||
if fee != 0 {
|
||||
messages.push(CosmosMsg::Bank(BankMsg::Send {
|
||||
to_address: relayer_address.to_string(),
|
||||
amount: coins_after_tax(deps, vec![coin(fee, &denom)])?,
|
||||
amount: vec![coin(fee, &denom)],
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -971,7 +1006,7 @@ fn handle_initiate_transfer(
|
|||
info: MessageInfo,
|
||||
asset: Asset,
|
||||
recipient_chain: u16,
|
||||
recipient: Vec<u8>,
|
||||
recipient: [u8; 32],
|
||||
fee: Uint128,
|
||||
transfer_type: TransferType<Vec<u8>>,
|
||||
nonce: u32,
|
||||
|
@ -1005,13 +1040,13 @@ fn handle_initiate_transfer(
|
|||
}
|
||||
|
||||
fn handle_initiate_transfer_token(
|
||||
mut deps: DepsMut,
|
||||
deps: DepsMut,
|
||||
env: Env,
|
||||
info: MessageInfo,
|
||||
asset: HumanAddr,
|
||||
mut amount: Uint128,
|
||||
recipient_chain: u16,
|
||||
recipient: Vec<u8>,
|
||||
recipient: [u8; 32],
|
||||
mut fee: Uint128,
|
||||
transfer_type: TransferType<Vec<u8>>,
|
||||
nonce: u32,
|
||||
|
@ -1024,7 +1059,7 @@ fn handle_initiate_transfer_token(
|
|||
}
|
||||
|
||||
let asset_chain: u16;
|
||||
let asset_address: Vec<u8>;
|
||||
let asset_address: [u8; 32];
|
||||
|
||||
let cfg: ConfigInfo = config_read(deps.storage).load()?;
|
||||
let asset_canonical: CanonicalAddr = deps.api.addr_canonicalize(&asset)?;
|
||||
|
@ -1032,7 +1067,7 @@ fn handle_initiate_transfer_token(
|
|||
let mut messages: Vec<CosmosMsg> = vec![];
|
||||
let mut submessages: Vec<SubMsg> = vec![];
|
||||
|
||||
match wrapped_asset_address_read(deps.storage).load(asset_canonical.as_slice()) {
|
||||
match is_wrapped_asset_read(deps.storage).load(asset_canonical.as_slice()) {
|
||||
Ok(_) => {
|
||||
// If the fee is too large the user will receive nothing.
|
||||
if fee > amount {
|
||||
|
@ -1052,17 +1087,16 @@ fn handle_initiate_transfer_token(
|
|||
contract_addr: asset,
|
||||
msg: to_binary(&WrappedQuery::WrappedAssetInfo {})?,
|
||||
});
|
||||
let wrapped_token_info: WrappedAssetInfoResponse =
|
||||
deps.querier.custom_query(&request)?;
|
||||
let wrapped_token_info: WrappedAssetInfoResponse = deps.querier.query(&request)?;
|
||||
asset_chain = wrapped_token_info.asset_chain;
|
||||
asset_address = wrapped_token_info.asset_address.into();
|
||||
asset_address = wrapped_token_info.asset_address.to_array()?;
|
||||
|
||||
let transfer_info = TransferInfo {
|
||||
token_chain: asset_chain,
|
||||
token_address: asset_address.clone(),
|
||||
token_address: ExternalTokenId::from_foreign_token(asset_chain, asset_address),
|
||||
amount: (0, amount.u128()),
|
||||
recipient_chain,
|
||||
recipient: recipient.clone(),
|
||||
recipient,
|
||||
fee: (0, fee.u128()),
|
||||
};
|
||||
|
||||
|
@ -1088,7 +1122,7 @@ fn handle_initiate_transfer_token(
|
|||
nonce,
|
||||
})?,
|
||||
// forward coins sent to this message
|
||||
funds: coins_after_tax(deps.branch(), info.funds.clone())?,
|
||||
funds: info.funds.clone(),
|
||||
}));
|
||||
}
|
||||
Err(_) => {
|
||||
|
@ -1130,8 +1164,14 @@ fn handle_initiate_transfer_token(
|
|||
1,
|
||||
));
|
||||
|
||||
asset_address = extend_address_to_32(&asset_canonical);
|
||||
asset_address = extend_address_to_32_array(&asset_canonical);
|
||||
asset_chain = CHAIN_ID;
|
||||
let address_human = deps.api.addr_humanize(&asset_canonical)?;
|
||||
// we store here just in case the token is transferred out before it's attested
|
||||
let external_id = TokenId::Contract(ContractId::NativeCW20 {
|
||||
contract_address: address_human,
|
||||
})
|
||||
.store(deps.storage)?;
|
||||
|
||||
// convert to normalized amounts before recording & posting vaa
|
||||
amount = Uint128::new(amount.u128().checked_div(multiplier).unwrap());
|
||||
|
@ -1139,7 +1179,7 @@ fn handle_initiate_transfer_token(
|
|||
|
||||
let transfer_info = TransferInfo {
|
||||
token_chain: asset_chain,
|
||||
token_address: asset_address.clone(),
|
||||
token_address: external_id,
|
||||
amount: (0, amount.u128()),
|
||||
recipient_chain,
|
||||
recipient: recipient.clone(),
|
||||
|
@ -1180,12 +1220,13 @@ fn handle_initiate_transfer_token(
|
|||
},
|
||||
};
|
||||
|
||||
let token_address = deps.api.addr_validate(&asset)?;
|
||||
|
||||
// Wrap up state to be captured by the submessage reply.
|
||||
wrapped_transfer_tmp(deps.storage).save(&TransferState {
|
||||
previous_balance: balance.balance.to_string(),
|
||||
account: info.sender.to_string(),
|
||||
token_address: asset,
|
||||
token_canonical: asset_canonical.clone(),
|
||||
token_address,
|
||||
message: token_bridge_message.serialize(),
|
||||
multiplier: Uint128::new(multiplier).to_string(),
|
||||
nonce,
|
||||
|
@ -1211,14 +1252,12 @@ fn handle_initiate_transfer_token(
|
|||
.add_attribute("transfer.block_time", env.block.time.seconds().to_string()))
|
||||
}
|
||||
|
||||
/// All ISO-4217 currency codes are 3 letters, so we can safely slice anything that is not ULUNA.
|
||||
/// https://www.xe.com/iso4217.php
|
||||
fn format_native_denom_symbol(denom: &str) -> String {
|
||||
if denom == "uluna" {
|
||||
return "LUNA".to_string();
|
||||
}
|
||||
// UUSD -> US -> UST
|
||||
denom.to_uppercase()[1..3].to_string() + "T"
|
||||
//TODO: is there better formatting to do here?
|
||||
denom.to_uppercase().to_string()
|
||||
}
|
||||
|
||||
fn handle_initiate_transfer_native_token(
|
||||
|
@ -1228,7 +1267,7 @@ fn handle_initiate_transfer_native_token(
|
|||
denom: String,
|
||||
amount: Uint128,
|
||||
recipient_chain: u16,
|
||||
recipient: Vec<u8>,
|
||||
recipient: [u8; 32],
|
||||
fee: Uint128,
|
||||
transfer_type: TransferType<Vec<u8>>,
|
||||
nonce: u32,
|
||||
|
@ -1255,17 +1294,14 @@ fn handle_initiate_transfer_native_token(
|
|||
let mut messages: Vec<CosmosMsg> = vec![];
|
||||
|
||||
let asset_chain: u16 = CHAIN_ID;
|
||||
let mut asset_address: Vec<u8> = build_native_id(&denom);
|
||||
// we store here just in case the token is transferred out before it's attested
|
||||
let asset_address = TokenId::Bank { denom }.store(deps.storage)?;
|
||||
|
||||
send_native(deps.storage, &asset_address[..].into(), amount)?;
|
||||
|
||||
// Mark the first byte of the address to distinguish it as native.
|
||||
asset_address = extend_address_to_32(&asset_address.into());
|
||||
asset_address[0] = 1;
|
||||
send_native(deps.storage, &asset_address, amount)?;
|
||||
|
||||
let transfer_info = TransferInfo {
|
||||
token_chain: asset_chain,
|
||||
token_address: asset_address.to_vec(),
|
||||
token_address: asset_address.clone(),
|
||||
amount: (0, amount.u128()),
|
||||
recipient_chain,
|
||||
recipient: recipient.clone(),
|
||||
|
@ -1294,13 +1330,13 @@ fn handle_initiate_transfer_native_token(
|
|||
message: Binary::from(token_bridge_message.serialize()),
|
||||
nonce,
|
||||
})?,
|
||||
funds: coins_after_tax(deps, info.funds.clone())?,
|
||||
funds: info.funds.clone(),
|
||||
}));
|
||||
|
||||
Ok(Response::new()
|
||||
.add_messages(messages)
|
||||
.add_attribute("transfer.token_chain", asset_chain.to_string())
|
||||
.add_attribute("transfer.token", hex::encode(asset_address))
|
||||
.add_attribute("transfer.token", hex::encode(asset_address.serialize()))
|
||||
.add_attribute(
|
||||
"transfer.sender",
|
||||
hex::encode(extend_address_to_32(&sender)),
|
||||
|
@ -1319,18 +1355,27 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
|
|||
to_binary(&query_wrapped_registry(deps, chain, address.as_slice())?)
|
||||
}
|
||||
QueryMsg::TransferInfo { vaa } => to_binary(&query_transfer_info(deps, env, &vaa)?),
|
||||
QueryMsg::ExternalId { external_id } => to_binary(&query_external_id(deps, external_id)?),
|
||||
}
|
||||
}
|
||||
|
||||
fn query_external_id(deps: Deps, external_id: Binary) -> StdResult<ExternalIdResponse> {
|
||||
let external_id = ExternalTokenId::deserialize(external_id.to_array()?);
|
||||
Ok(ExternalIdResponse {
|
||||
token_id: external_id.to_token_id(deps.storage, CHAIN_ID)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn query_wrapped_registry(
|
||||
deps: Deps,
|
||||
chain: u16,
|
||||
address: &[u8],
|
||||
) -> StdResult<WrappedRegistryResponse> {
|
||||
let asset_id = build_asset_id(chain, address);
|
||||
// Check if this asset is already deployed
|
||||
match wrapped_asset_read(deps.storage).load(&asset_id) {
|
||||
Ok(address) => Ok(WrappedRegistryResponse { address }),
|
||||
match wrapped_asset_read(deps.storage, chain).load(&address) {
|
||||
Ok(address) => Ok(WrappedRegistryResponse {
|
||||
address: address.into_string(),
|
||||
}),
|
||||
Err(_) => ContractError::AssetNotFound.std_err(),
|
||||
}
|
||||
}
|
||||
|
@ -1355,7 +1400,7 @@ fn query_transfer_info(deps: Deps, env: Env, vaa: &Binary) -> StdResult<Transfer
|
|||
|
||||
Ok(TransferInfoResponse {
|
||||
amount: core.amount.1.into(),
|
||||
token_address: core.token_address,
|
||||
token_address: core.token_address.serialize(),
|
||||
token_chain: core.token_chain,
|
||||
recipient: core.recipient,
|
||||
recipient_chain: core.recipient_chain,
|
||||
|
@ -1366,27 +1411,6 @@ fn query_transfer_info(deps: Deps, env: Env, vaa: &Binary) -> StdResult<Transfer
|
|||
}
|
||||
}
|
||||
|
||||
pub fn build_asset_id(chain: u16, address: &[u8]) -> Vec<u8> {
|
||||
let chain = &chain.to_be_bytes();
|
||||
let mut asset_id = Vec::with_capacity(chain.len() + address.len());
|
||||
asset_id.extend_from_slice(chain);
|
||||
asset_id.extend_from_slice(address);
|
||||
|
||||
let mut hasher = Keccak256::new();
|
||||
hasher.update(asset_id);
|
||||
hasher.finalize().to_vec()
|
||||
}
|
||||
|
||||
// Produce a 20 byte asset "address" from a native terra denom.
|
||||
pub fn build_native_id(denom: &str) -> Vec<u8> {
|
||||
let n = denom.len();
|
||||
assert!(n < 20);
|
||||
let mut asset_address = Vec::with_capacity(20);
|
||||
asset_address.resize(20 - n, 0u8);
|
||||
asset_address.extend_from_slice(denom.as_bytes());
|
||||
asset_address
|
||||
}
|
||||
|
||||
fn is_governance_emitter(cfg: &ConfigInfo, emitter_chain: u16, emitter_address: &Vec<u8>) -> bool {
|
||||
cfg.gov_chain == emitter_chain && cfg.gov_address == emitter_address.clone()
|
||||
}
|
||||
|
|
|
@ -4,6 +4,10 @@ extern crate lazy_static;
|
|||
pub mod contract;
|
||||
pub mod msg;
|
||||
pub mod state;
|
||||
pub mod token_address;
|
||||
|
||||
#[cfg(test)]
|
||||
mod testing;
|
||||
|
||||
// Chain ID of Terra 2.0
|
||||
pub const CHAIN_ID: u16 = 18;
|
||||
|
|
|
@ -12,6 +12,11 @@ use terraswap::asset::{
|
|||
AssetInfo,
|
||||
};
|
||||
|
||||
use crate::token_address::{
|
||||
ExternalTokenId,
|
||||
TokenId,
|
||||
};
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
|
@ -28,7 +33,8 @@ pub struct InstantiateMsg {
|
|||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ExecuteMsg {
|
||||
RegisterAssetHook {
|
||||
asset_id: Binary,
|
||||
chain: u16,
|
||||
token_address: ExternalTokenId,
|
||||
},
|
||||
|
||||
DepositTokens {},
|
||||
|
@ -77,6 +83,7 @@ pub struct MigrateMsg {}
|
|||
pub enum QueryMsg {
|
||||
WrappedRegistry { chain: u16, address: Binary },
|
||||
TransferInfo { vaa: Binary },
|
||||
ExternalId { external_id: Binary },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
|
@ -89,10 +96,16 @@ pub struct WrappedRegistryResponse {
|
|||
#[serde(rename_all = "snake_case")]
|
||||
pub struct TransferInfoResponse {
|
||||
pub amount: Uint128,
|
||||
pub token_address: Vec<u8>,
|
||||
pub token_address: [u8; 32],
|
||||
pub token_chain: u16,
|
||||
pub recipient: Vec<u8>,
|
||||
pub recipient: [u8; 32],
|
||||
pub recipient_chain: u16,
|
||||
pub fee: Uint128,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub struct ExternalIdResponse {
|
||||
pub token_id: TokenId,
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ use serde::{
|
|||
};
|
||||
|
||||
use cosmwasm_std::{
|
||||
CanonicalAddr,
|
||||
Addr,
|
||||
StdError,
|
||||
StdResult,
|
||||
Storage,
|
||||
|
@ -24,6 +24,8 @@ use cosmwasm_storage::{
|
|||
|
||||
use wormhole::byte_utils::ByteUtils;
|
||||
|
||||
use crate::token_address::{ExternalTokenId, WrappedCW20};
|
||||
|
||||
type HumanAddr = String;
|
||||
|
||||
pub static CONFIG_KEY: &[u8] = b"config";
|
||||
|
@ -34,6 +36,8 @@ pub static WRAPPED_ASSET_ADDRESS_KEY: &[u8] = b"wrapped_asset_address";
|
|||
pub static BRIDGE_CONTRACTS: &[u8] = b"bridge_contracts";
|
||||
pub static BRIDGE_DEPOSITS: &[u8] = b"bridge_deposits";
|
||||
pub static NATIVE_COUNTER: &[u8] = b"native_counter";
|
||||
pub static BANK_TOKEN_HASHES_KEY: &[u8] = b"bank_token_hashes";
|
||||
pub static NATIVE_CW20_HASHES_KEY: &[u8] = b"native_cw20_hashes";
|
||||
|
||||
// Guardian set information
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
|
@ -70,30 +74,46 @@ pub fn bridge_contracts_read(storage: &dyn Storage) -> ReadonlyBucket<Vec<u8>> {
|
|||
bucket_read(storage, BRIDGE_CONTRACTS)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset(storage: &mut dyn Storage) -> Bucket<HumanAddr> {
|
||||
bucket(storage, WRAPPED_ASSET_KEY)
|
||||
pub fn wrapped_asset(storage: &mut dyn Storage, chain: u16) -> Bucket<WrappedCW20> {
|
||||
Bucket::multilevel(storage, &[WRAPPED_ASSET_KEY, &chain.to_be_bytes()])
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_read(storage: &dyn Storage) -> ReadonlyBucket<HumanAddr> {
|
||||
bucket_read(storage, WRAPPED_ASSET_KEY)
|
||||
pub fn wrapped_asset_read(storage: &dyn Storage, chain: u16) -> ReadonlyBucket<WrappedCW20> {
|
||||
ReadonlyBucket::multilevel(storage, &[WRAPPED_ASSET_KEY, &chain.to_be_bytes()])
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_seq(storage: &mut dyn Storage) -> Bucket<u64> {
|
||||
bucket(storage, WRAPPED_ASSET_SEQ_KEY)
|
||||
pub fn wrapped_asset_seq(storage: &mut dyn Storage, chain: u16) -> Bucket<u64> {
|
||||
Bucket::multilevel(storage, &[WRAPPED_ASSET_KEY, &chain.to_be_bytes()])
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_seq_read(storage: &mut dyn Storage) -> ReadonlyBucket<u64> {
|
||||
bucket_read(storage, WRAPPED_ASSET_SEQ_KEY)
|
||||
pub fn wrapped_asset_seq_read(storage: &mut dyn Storage, chain: u16) -> ReadonlyBucket<u64> {
|
||||
ReadonlyBucket::multilevel(storage, &[WRAPPED_ASSET_KEY, &chain.to_be_bytes()])
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_address(storage: &mut dyn Storage) -> Bucket<Vec<u8>> {
|
||||
pub fn is_wrapped_asset(storage: &mut dyn Storage) -> Bucket<()> {
|
||||
bucket(storage, WRAPPED_ASSET_ADDRESS_KEY)
|
||||
}
|
||||
|
||||
pub fn wrapped_asset_address_read(storage: &dyn Storage) -> ReadonlyBucket<Vec<u8>> {
|
||||
pub fn is_wrapped_asset_read(storage: &dyn Storage) -> ReadonlyBucket<()> {
|
||||
bucket_read(storage, WRAPPED_ASSET_ADDRESS_KEY)
|
||||
}
|
||||
|
||||
pub fn bank_token_hashes(storage: &mut dyn Storage) -> Bucket<String> {
|
||||
bucket(storage, BANK_TOKEN_HASHES_KEY)
|
||||
}
|
||||
|
||||
pub fn bank_token_hashes_read(storage: &dyn Storage) -> ReadonlyBucket<String> {
|
||||
bucket_read(storage, BANK_TOKEN_HASHES_KEY)
|
||||
}
|
||||
|
||||
pub fn native_c20_hashes(storage: &mut dyn Storage) -> Bucket<Addr> {
|
||||
bucket(storage, NATIVE_CW20_HASHES_KEY)
|
||||
}
|
||||
|
||||
pub fn native_c20_hashes_read(storage: &dyn Storage) -> ReadonlyBucket<Addr> {
|
||||
bucket_read(storage, NATIVE_CW20_HASHES_KEY)
|
||||
}
|
||||
|
||||
type Serialized128 = String;
|
||||
|
||||
/// Structure to keep track of an active CW20 transfer, required to pass state through to the reply
|
||||
|
@ -105,8 +125,7 @@ pub struct TransferState {
|
|||
pub multiplier: Serialized128,
|
||||
pub nonce: u32,
|
||||
pub previous_balance: Serialized128,
|
||||
pub token_address: HumanAddr,
|
||||
pub token_canonical: CanonicalAddr,
|
||||
pub token_address: Addr,
|
||||
}
|
||||
|
||||
pub fn wrapped_transfer_tmp(storage: &mut dyn Storage) -> Singleton<TransferState> {
|
||||
|
@ -115,31 +134,31 @@ pub fn wrapped_transfer_tmp(storage: &mut dyn Storage) -> Singleton<TransferStat
|
|||
|
||||
pub fn send_native(
|
||||
storage: &mut dyn Storage,
|
||||
asset_address: &CanonicalAddr,
|
||||
asset_address: &ExternalTokenId,
|
||||
amount: Uint128,
|
||||
) -> StdResult<()> {
|
||||
let mut counter_bucket = bucket(storage, NATIVE_COUNTER);
|
||||
let new_total = amount
|
||||
+ counter_bucket
|
||||
.load(asset_address.as_slice())
|
||||
.load(asset_address.serialize().as_slice())
|
||||
.unwrap_or(Uint128::zero());
|
||||
if new_total > Uint128::new(u64::MAX as u128) {
|
||||
return Err(StdError::generic_err(
|
||||
"transfer exceeds max outstanding bridged token amount",
|
||||
));
|
||||
}
|
||||
counter_bucket.save(asset_address.as_slice(), &new_total)
|
||||
counter_bucket.save(asset_address.serialize().as_slice(), &new_total)
|
||||
}
|
||||
|
||||
pub fn receive_native(
|
||||
storage: &mut dyn Storage,
|
||||
asset_address: &CanonicalAddr,
|
||||
asset_address: &ExternalTokenId,
|
||||
amount: Uint128,
|
||||
) -> StdResult<()> {
|
||||
let mut counter_bucket = bucket(storage, NATIVE_COUNTER);
|
||||
let total: Uint128 = counter_bucket.load(asset_address.as_slice())?;
|
||||
let total: Uint128 = counter_bucket.load(asset_address.serialize().as_slice())?;
|
||||
let result = total.checked_sub(amount)?;
|
||||
counter_bucket.save(asset_address.as_slice(), &result)
|
||||
counter_bucket.save(asset_address.serialize().as_slice(), &result)
|
||||
}
|
||||
|
||||
pub struct Action;
|
||||
|
@ -185,9 +204,9 @@ impl TokenBridgeMessage {
|
|||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub struct TransferInfo {
|
||||
pub amount: (u128, u128),
|
||||
pub token_address: Vec<u8>,
|
||||
pub token_address: ExternalTokenId,
|
||||
pub token_chain: u16,
|
||||
pub recipient: Vec<u8>,
|
||||
pub recipient: [u8; 32],
|
||||
pub recipient_chain: u16,
|
||||
pub fee: (u128, u128),
|
||||
}
|
||||
|
@ -196,9 +215,9 @@ impl TransferInfo {
|
|||
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
|
||||
let data = data.as_slice();
|
||||
let amount = data.get_u256(0);
|
||||
let token_address = data.get_bytes32(32).to_vec();
|
||||
let token_address = ExternalTokenId::deserialize(data.get_const_bytes::<32>(32));
|
||||
let token_chain = data.get_u16(64);
|
||||
let recipient = data.get_bytes32(66).to_vec();
|
||||
let recipient = data.get_const_bytes::<32>(66);
|
||||
let recipient_chain = data.get_u16(98);
|
||||
let fee = data.get_u256(100);
|
||||
|
||||
|
@ -215,7 +234,7 @@ impl TransferInfo {
|
|||
[
|
||||
self.amount.0.to_be_bytes().to_vec(),
|
||||
self.amount.1.to_be_bytes().to_vec(),
|
||||
self.token_address.clone(),
|
||||
self.token_address.serialize().to_vec(),
|
||||
self.token_chain.to_be_bytes().to_vec(),
|
||||
self.recipient.to_vec(),
|
||||
self.recipient_chain.to_be_bytes().to_vec(),
|
||||
|
@ -265,7 +284,7 @@ impl TransferWithPayloadInfo {
|
|||
// 67 [32]uint8 Name
|
||||
|
||||
pub struct AssetMeta {
|
||||
pub token_address: Vec<u8>,
|
||||
pub token_address: ExternalTokenId,
|
||||
pub token_chain: u16,
|
||||
pub decimals: u8,
|
||||
pub symbol: Vec<u8>,
|
||||
|
@ -275,7 +294,7 @@ pub struct AssetMeta {
|
|||
impl AssetMeta {
|
||||
pub fn deserialize(data: &Vec<u8>) -> StdResult<Self> {
|
||||
let data = data.as_slice();
|
||||
let token_address = data.get_bytes32(0).to_vec();
|
||||
let token_address = ExternalTokenId::deserialize(data.get_const_bytes::<32>(0));
|
||||
let token_chain = data.get_u16(32);
|
||||
let decimals = data.get_u8(34);
|
||||
let symbol = data.get_bytes32(35).to_vec();
|
||||
|
@ -292,7 +311,7 @@ impl AssetMeta {
|
|||
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
[
|
||||
self.token_address.clone(),
|
||||
self.token_address.serialize().to_vec(),
|
||||
self.token_chain.to_be_bytes().to_vec(),
|
||||
self.decimals.to_be_bytes().to_vec(),
|
||||
self.symbol.clone(),
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
use std::convert::TryInto;
|
||||
|
||||
use cosmwasm_std::{
|
||||
Binary,
|
||||
StdResult,
|
||||
|
@ -6,16 +8,13 @@ use cosmwasm_std::{
|
|||
use wormhole::state::ParsedVAA;
|
||||
|
||||
use crate::{
|
||||
contract::{
|
||||
build_asset_id,
|
||||
build_native_id,
|
||||
},
|
||||
state::{
|
||||
Action,
|
||||
TokenBridgeMessage,
|
||||
TransferInfo,
|
||||
TransferWithPayloadInfo,
|
||||
},
|
||||
token_address::ExternalTokenId,
|
||||
};
|
||||
|
||||
#[test]
|
||||
|
@ -52,27 +51,31 @@ fn binary_check() -> StdResult<()> {
|
|||
|
||||
#[test]
|
||||
fn build_native_and_asset_ids() -> StdResult<()> {
|
||||
let denom = "uusd";
|
||||
let native_id = build_native_id(denom);
|
||||
let external_id_uluna = ExternalTokenId::from_bank_token(&"uluna".to_string())?;
|
||||
|
||||
let expected_native_id = vec![
|
||||
0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 117u8,
|
||||
117u8, 115u8, 100u8,
|
||||
];
|
||||
assert_eq!(&native_id, &expected_native_id, "native_id != expected");
|
||||
let expected_external_id: [u8; 32] = [1, 250, 108, 111, 188, 54, 216, 194, 69, 176, 168, 82, 164, 62, 181, 214, 68, 232, 180, 196, 119, 178, 123, 250, 185, 83, 124, 16, 148, 89, 57, 218];
|
||||
assert_eq!(
|
||||
&external_id_uluna.serialize(),
|
||||
&expected_external_id,
|
||||
"external_id != expected"
|
||||
);
|
||||
|
||||
// weth
|
||||
let chain = 2u16;
|
||||
let token_address = "000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
|
||||
let token_address = hex::decode(token_address).unwrap();
|
||||
let asset_id = build_asset_id(chain, token_address.as_slice());
|
||||
let token_address: [u8; 32] = hex::decode(token_address)
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.unwrap();
|
||||
let external_id_weth = ExternalTokenId::from_foreign_token(chain, token_address);
|
||||
|
||||
let expected_asset_id = vec![
|
||||
171u8, 106u8, 233u8, 80u8, 14u8, 139u8, 124u8, 78u8, 181u8, 77u8, 142u8, 76u8, 109u8, 81u8,
|
||||
55u8, 100u8, 139u8, 159u8, 42u8, 85u8, 172u8, 234u8, 0u8, 114u8, 11u8, 82u8, 40u8, 40u8,
|
||||
50u8, 73u8, 211u8, 135u8,
|
||||
];
|
||||
assert_eq!(&asset_id, &expected_asset_id, "asset_id != expected");
|
||||
let expected_asset_id: [u8; 32] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 42, 170, 57, 178, 35, 254, 141, 10, 14, 92, 79, 39, 234, 217, 8, 60, 117, 108, 194];
|
||||
assert_eq!(
|
||||
&external_id_weth.serialize(),
|
||||
&expected_asset_id,
|
||||
"asset_id != expected"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
@ -105,7 +108,8 @@ fn deserialize_transfer_vaa() -> StdResult<()> {
|
|||
let token_address = "0100000000000000000000000000000000000000000000000000000075757364";
|
||||
let token_address = hex::decode(token_address).unwrap();
|
||||
assert_eq!(
|
||||
info.token_address, token_address,
|
||||
info.token_address.serialize().to_vec(),
|
||||
token_address,
|
||||
"info.token_address != expected"
|
||||
);
|
||||
|
||||
|
@ -117,7 +121,11 @@ fn deserialize_transfer_vaa() -> StdResult<()> {
|
|||
|
||||
let recipient = "000000000000000000000000f7f7dde848e7450a029cd0a9bd9bdae4b5147db3";
|
||||
let recipient = hex::decode(recipient).unwrap();
|
||||
assert_eq!(info.recipient, recipient, "info.recipient != expected");
|
||||
assert_eq!(
|
||||
info.recipient.to_vec(),
|
||||
recipient,
|
||||
"info.recipient != expected"
|
||||
);
|
||||
|
||||
let recipient_chain = 3u16;
|
||||
assert_eq!(
|
||||
|
@ -162,7 +170,8 @@ fn deserialize_transfer_with_payload_vaa() -> StdResult<()> {
|
|||
let token_address = "0100000000000000000000000000000000000000000000000000000075757364";
|
||||
let token_address = hex::decode(token_address).unwrap();
|
||||
assert_eq!(
|
||||
info.token_address, token_address,
|
||||
info.token_address.serialize().to_vec(),
|
||||
token_address,
|
||||
"info.token_address != expected"
|
||||
);
|
||||
|
||||
|
@ -174,7 +183,11 @@ fn deserialize_transfer_with_payload_vaa() -> StdResult<()> {
|
|||
|
||||
let recipient = "0000000000000000000000008cec800d24df11e556e708461c98122df4a2c3b1";
|
||||
let recipient = hex::decode(recipient).unwrap();
|
||||
assert_eq!(info.recipient, recipient, "info.recipient != expected");
|
||||
assert_eq!(
|
||||
info.recipient.to_vec(),
|
||||
recipient,
|
||||
"info.recipient != expected"
|
||||
);
|
||||
|
||||
let recipient_chain = 3u16;
|
||||
assert_eq!(
|
||||
|
|
|
@ -0,0 +1,228 @@
|
|||
use cosmwasm_std::{
|
||||
Addr,
|
||||
StdError,
|
||||
StdResult,
|
||||
Storage,
|
||||
};
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{
|
||||
Deserialize,
|
||||
Serialize,
|
||||
};
|
||||
use sha3::{
|
||||
Digest,
|
||||
Keccak256,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
state::{
|
||||
bank_token_hashes,
|
||||
bank_token_hashes_read,
|
||||
native_c20_hashes,
|
||||
native_c20_hashes_read,
|
||||
},
|
||||
CHAIN_ID,
|
||||
};
|
||||
|
||||
/// Represent the external view of a token address.
|
||||
/// This is the value that goes into the VAA.
|
||||
///
|
||||
/// When given an external 32 byte address, there are 3 options:
|
||||
/// I. This is a token native to this chain
|
||||
/// a. it's a token managed by the Bank cosmos module
|
||||
/// (e.g. the staking denom "uluna" on Terra)
|
||||
/// b. it's a CW20 token
|
||||
/// II. This is a token address from another chain
|
||||
///
|
||||
/// Thus, interpreting an external token id requires knowing whether the token
|
||||
/// in question originates from this chain, or another chain. This information
|
||||
/// will always be available from the context.
|
||||
///
|
||||
/// I. //////////////////////////////////////////////////////////////////////////
|
||||
///
|
||||
/// In the first case (native tokens), the layout of is the following:
|
||||
///
|
||||
/// | 1 byte | 31 bytes |
|
||||
/// +--------+-----------------------------------------------------------------+
|
||||
/// | MARKER | HASH |
|
||||
/// +--------+-----------------------------------------------------------------+
|
||||
///
|
||||
/// The left-most byte (MARKER) tells us whether it's a Bank token (1), or a CW20 (0).
|
||||
/// Since denom names can be arbitarily long, and CW20 addresses are 32 byes, we
|
||||
/// cannot directly encode them into the remaining 31 bytes. Instead, we hash
|
||||
/// the data (either the denom or the CW20 address), and put the last 31 bytes
|
||||
/// of the hash into the address (HASH). In particular, this choice reduces the
|
||||
/// space of the hash function by 8 bits, but assuming the hash is resistant to
|
||||
/// differential attacks, we consider giving up on these 8 bits safe.
|
||||
///
|
||||
/// In order to be able to recover the denom and the contract address later, we
|
||||
/// store a mapping from these 32 bytes (MARKER+HASH) to denoms and CW20
|
||||
/// addresses (c.f. [`native_cw20_hashes`] & [`bank_token_hashes`] in state.rs)
|
||||
///
|
||||
/// II. /////////////////////////////////////////////////////////////////////////
|
||||
///
|
||||
/// In the second case (foreign tokens), the whole 32 bytes correspond to the
|
||||
/// external token address. In this case, the corresponding token will be a
|
||||
/// wrapped asset, whose address is stored in storage as a mapping (c.f.
|
||||
/// [`wrapped_asset`] in state.rs)
|
||||
///
|
||||
/// (chain_id, external_id) => wrapped_asset_address
|
||||
///
|
||||
/// For internal consumption of these addresses, we first convert them to
|
||||
/// [`TokenId`] (see below).
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[repr(transparent)]
|
||||
pub struct ExternalTokenId {
|
||||
bytes: [u8; 32],
|
||||
}
|
||||
|
||||
/// The intention is that [`ExternalTokenId`] should always be converted to/from
|
||||
/// [`TokenId`] through the functions defined in this module. This is why its
|
||||
/// internal contents are private. The following functions are called
|
||||
/// [`serialize`] and [`deserialize`] to signify that they should only be used
|
||||
/// when converting back and forth the wire format.
|
||||
impl ExternalTokenId {
|
||||
pub fn serialize(&self) -> [u8; 32] {
|
||||
self.bytes
|
||||
}
|
||||
|
||||
pub fn deserialize(data: [u8; 32]) -> Self {
|
||||
Self { bytes: data }
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalTokenId {
|
||||
pub fn to_token_id(&self, storage: &dyn Storage, origin_chain: u16) -> StdResult<TokenId> {
|
||||
if origin_chain == CHAIN_ID {
|
||||
let marker_byte = self.bytes[0];
|
||||
match marker_byte {
|
||||
1 => {
|
||||
let denom = bank_token_hashes_read(storage).load(&self.bytes)?;
|
||||
Ok(TokenId::Bank { denom })
|
||||
}
|
||||
0 => {
|
||||
let human_address = native_c20_hashes_read(storage).load(&self.bytes)?;
|
||||
Ok(TokenId::Contract(ContractId::NativeCW20 {
|
||||
contract_address: human_address,
|
||||
}))
|
||||
}
|
||||
b => Err(StdError::generic_err(format!("Unknown marker byte: {}", b))),
|
||||
}
|
||||
} else {
|
||||
Ok(TokenId::Contract(ContractId::ForeignToken {
|
||||
chain_id: origin_chain,
|
||||
foreign_address: self.bytes,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_native_cw20(contract_address: &Addr) -> StdResult<ExternalTokenId> {
|
||||
let mut hash = hash(contract_address.as_bytes());
|
||||
// override first byte with marker byte
|
||||
hash[0] = 0;
|
||||
Ok(ExternalTokenId { bytes: hash })
|
||||
}
|
||||
|
||||
pub fn from_foreign_token(chain_id: u16, foreign_address: [u8; 32]) -> ExternalTokenId {
|
||||
assert!(chain_id != CHAIN_ID, "Expected a foreign chain id.");
|
||||
ExternalTokenId {
|
||||
bytes: foreign_address,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_bank_token(denom: &String) -> StdResult<ExternalTokenId> {
|
||||
let mut hash = hash(&denom.as_bytes());
|
||||
// override first byte with marker byte
|
||||
hash[0] = 1;
|
||||
Ok(ExternalTokenId { bytes: hash })
|
||||
}
|
||||
|
||||
pub fn from_token_id(token_id: &TokenId) -> StdResult<ExternalTokenId> {
|
||||
match token_id {
|
||||
TokenId::Bank { denom } => Self::from_bank_token(denom),
|
||||
TokenId::Contract(contract) => match contract {
|
||||
ContractId::NativeCW20 { contract_address } => {
|
||||
Self::from_native_cw20(contract_address)
|
||||
}
|
||||
ContractId::ForeignToken {
|
||||
chain_id,
|
||||
foreign_address,
|
||||
} => Ok(Self::from_foreign_token(*chain_id, *foreign_address)),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal view of an address. This type is similar to [`AssetInfo`], but more
|
||||
/// granular. We do differentiate between bank tokens and CW20 tokens, but in
|
||||
/// the latter case, we further differentiate between native CW20s and wrapped
|
||||
/// CW20s (see [`ContractId`]).
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub enum TokenId {
|
||||
Bank { denom: String },
|
||||
Contract(ContractId),
|
||||
}
|
||||
|
||||
impl TokenId {
|
||||
/// Given a [`TokenId`], we can always directly construct an
|
||||
/// [`ExternalTokenId`], but the converse is not true, since the
|
||||
/// construction of external ids involves hashing, and is thus irreversible.
|
||||
/// To maintain the bijection (modulo hash collisions), we store the hash
|
||||
/// preimages in storage, so given an external id, the necessary information
|
||||
/// can always be queried to reconstruct the token id.
|
||||
/// This information must be stored when the token id is first converted to
|
||||
/// an external id, i.e. when an attestation is generated for the token.
|
||||
pub fn store(&self, storage: &mut dyn Storage) -> StdResult<ExternalTokenId> {
|
||||
let external_id = ExternalTokenId::from_token_id(self)?;
|
||||
match self {
|
||||
TokenId::Bank { denom } => bank_token_hashes(storage).save(&external_id.bytes, denom),
|
||||
TokenId::Contract(contract) => match contract {
|
||||
ContractId::NativeCW20 { contract_address } => {
|
||||
native_c20_hashes(storage).save(&external_id.bytes, &contract_address)
|
||||
}
|
||||
ContractId::ForeignToken {
|
||||
chain_id: _,
|
||||
foreign_address: _,
|
||||
} => Err(StdError::generic_err(
|
||||
"Foreign tokens are not stored in storage",
|
||||
)),
|
||||
},
|
||||
}?;
|
||||
Ok(external_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// A contract id is either a native cw20 address, or a foreign token. The
|
||||
/// reason we represent the foreign address here instead of storing the wrapped
|
||||
/// CW20 contract's address directly is that the wrapped asset might not be
|
||||
/// deployed yet.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
pub enum ContractId {
|
||||
NativeCW20 {
|
||||
contract_address: Addr,
|
||||
},
|
||||
/// A wrapped token might not exist yet.
|
||||
ForeignToken {
|
||||
chain_id: u16,
|
||||
foreign_address: [u8; 32],
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||
#[repr(transparent)]
|
||||
pub struct WrappedCW20 {
|
||||
pub human_address: Addr,
|
||||
}
|
||||
|
||||
impl WrappedCW20 {
|
||||
pub fn into_string(self) -> String {
|
||||
self.human_address.into_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn hash(bytes: &[u8]) -> [u8; 32] {
|
||||
let mut hasher = Keccak256::new();
|
||||
hasher.update(bytes);
|
||||
hasher.finalize().into()
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
[package]
|
||||
name = "wormhole-bridge-terra"
|
||||
name = "wormhole-bridge-terra-2"
|
||||
version = "0.1.0"
|
||||
authors = ["Yuriy Savchenko <yuriy.savchenko@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
@ -15,14 +15,14 @@ backtraces = ["cosmwasm-std/backtraces"]
|
|||
library = []
|
||||
|
||||
[dependencies]
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
cosmwasm-storage = { version = "0.16.0" }
|
||||
schemars = "0.8.1"
|
||||
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
|
||||
cw20 = "0.8.0"
|
||||
cw20-base = { version = "0.8.0", features = ["library"] }
|
||||
cw20-wrapped = { path = "../cw20-wrapped", features = ["library"] }
|
||||
thiserror = { version = "1.0.20" }
|
||||
cosmwasm-std = { version = "1.0.0" }
|
||||
cosmwasm-storage = { version = "1.0.0" }
|
||||
schemars = "0.8.8"
|
||||
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
|
||||
cw20 = "0.13.2"
|
||||
cw20-base = { version = "0.13.2", features = ["library"] }
|
||||
cw20-wrapped-2 = { path = "../cw20-wrapped", features = ["library"] }
|
||||
thiserror = { version = "1.0.31" }
|
||||
k256 = { version = "0.9.4", default-features = false, features = ["ecdsa"] }
|
||||
getrandom = { version = "0.2", features = ["custom"] }
|
||||
sha3 = { version = "0.9.1", default-features = false }
|
||||
|
|
|
@ -43,8 +43,12 @@ impl ByteUtils for &[u8] {
|
|||
(self.get_u128_be(index), self.get_u128_be(index + 128 / 8))
|
||||
}
|
||||
fn get_address(&self, index: usize) -> CanonicalAddr {
|
||||
// 32 bytes are reserved for addresses, but only the last 20 bytes are taken by the actual address
|
||||
CanonicalAddr::from(&self[index + 32 - 20..index + 32])
|
||||
// 32 bytes are reserved for addresses, but wasmd uses both 32 and 20 bytes
|
||||
// https://github.com/CosmWasm/wasmd/blob/ac92fdcf37388cc8dc24535f301f64395f8fb3da/x/wasm/types/types.go#L325
|
||||
if self.get_u128_be(index) >> 32 == 0 {
|
||||
return CanonicalAddr::from(&self[index + 12..index + 32])
|
||||
}
|
||||
return CanonicalAddr::from(&self[index..index + 32])
|
||||
}
|
||||
fn get_bytes32(&self, index: usize) -> &[u8] {
|
||||
&self[index..index + 32]
|
||||
|
@ -61,13 +65,13 @@ impl ByteUtils for &[u8] {
|
|||
}
|
||||
}
|
||||
|
||||
/// Left-pad a 20 byte address with 0s
|
||||
/// Left-pad a <= 32 byte address with 0s
|
||||
pub fn extend_address_to_32(addr: &CanonicalAddr) -> Vec<u8> {
|
||||
extend_address_to_32_array(addr).to_vec()
|
||||
}
|
||||
|
||||
pub fn extend_address_to_32_array(addr: &CanonicalAddr) -> [u8; 32] {
|
||||
let mut v: Vec<u8> = vec![0; 12];
|
||||
let mut v: Vec<u8> = vec![0; 32 - addr.len()];
|
||||
v.extend(addr.as_slice());
|
||||
let mut result: [u8; 32] = [0; 32];
|
||||
result.copy_from_slice(&v);
|
||||
|
|
|
@ -76,8 +76,8 @@ use std::convert::TryFrom;
|
|||
|
||||
type HumanAddr = String;
|
||||
|
||||
// Chain ID of Terra
|
||||
const CHAIN_ID: u16 = 3;
|
||||
// Chain ID of Terra 2.0
|
||||
const CHAIN_ID: u16 = 18;
|
||||
|
||||
// Lock assets fee amount and denomination
|
||||
const FEE_AMOUNT: u128 = 0;
|
||||
|
|
|
@ -40,7 +40,7 @@ fn get_config_info<S: Storage>(storage: &S) -> ConfigInfo {
|
|||
}
|
||||
|
||||
fn do_init(guardians: &[GuardianAddress]) -> OwnedDeps<MockStorage, MockApi, MockQuerier> {
|
||||
let mut deps = mock_dependencies(&[]);
|
||||
let mut deps = mock_dependencies();
|
||||
let init_msg = InstantiateMsg {
|
||||
gov_chain: 0,
|
||||
gov_address: GOV_ADDR.into(),
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
FROM terramoney/localterra-core:bombay@sha256:0f93576ae0716f835b2adbd5ac550ef90063b536e99c4dd682b6dd905927f261
|
||||
FROM terramoney/localterra-core:2.0.1@sha256:73faa857d32b869b6bd3bf062351bd47ca5440d758dc07d5481424b9a9bdaede
|
||||
|
||||
ADD config /root/.terra/config
|
||||
|
|
|
@ -8,11 +8,11 @@
|
|||
# The minimum gas prices a validator is willing to accept for processing a
|
||||
# transaction. A transaction's fees must meet the minimum of any denomination
|
||||
# specified in this config (e.g. 0.25token1;0.0001token2).
|
||||
minimum-gas-prices = "0.01133uluna,0.15uusd,0.104938usdr,169.77ukrw,428.571umnt,0.125ueur,0.98ucny,16.37ujpy,0.11ugbp,10.88uinr,0.19ucad,0.14uchf,0.19uaud,0.2usgd,4.62uthb,1.25usek"
|
||||
minimum-gas-prices = "0.15uluna"
|
||||
|
||||
# default: the last 100 states are kept in addition to every 500th state; pruning at 10 block intervals
|
||||
# nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node)
|
||||
# everything: all saved states will be deleted, storing only the current state; pruning at 10 block intervals
|
||||
# everything: all saved states will be deleted, storing only the current and previous state; pruning at 10 block intervals
|
||||
# custom: allow pruning options to be manually specified through 'pruning-keep-recent', 'pruning-keep-every', and 'pruning-interval'
|
||||
pruning = "default"
|
||||
|
||||
|
@ -44,7 +44,7 @@ halt-time = 0
|
|||
# It has no bearing on application state pruning which is determined by the
|
||||
# "pruning-*" configurations.
|
||||
#
|
||||
# Note: Tendermint block pruning is dependant on this parameter in conjunction
|
||||
# Note: Tendermint block pruning is dependant on this parameter in conunction
|
||||
# with the unbonding (safety threshold) period, state pruning and state sync
|
||||
# snapshot parameters to determine the correct minimum value of
|
||||
# ResponseCommit.RetainHeight.
|
||||
|
@ -60,6 +60,10 @@ inter-block-cache = true
|
|||
# ["message.sender", "message.recipient"]
|
||||
index-events = []
|
||||
|
||||
# IavlCacheSize set the size of the iavl tree cache.
|
||||
# Default cache size is 50mb.
|
||||
iavl-cache-size = 781250
|
||||
|
||||
###############################################################################
|
||||
### Telemetry Configuration ###
|
||||
###############################################################################
|
||||
|
@ -116,7 +120,7 @@ max-open-connections = 1000
|
|||
rpc-read-timeout = 10
|
||||
|
||||
# RPCWriteTimeout defines the Tendermint RPC write timeout (in seconds).
|
||||
rpc-write-timeout = 30
|
||||
rpc-write-timeout = 0
|
||||
|
||||
# RPCMaxBodyBytes defines the Tendermint maximum response body (in bytes).
|
||||
rpc-max-body-bytes = 1000000
|
||||
|
@ -192,15 +196,8 @@ snapshot-interval = 0
|
|||
snapshot-keep-recent = 2
|
||||
|
||||
[wasm]
|
||||
# The maximum gas amount can be spent for contract query.
|
||||
# The contract query will invoke contract execution vm,
|
||||
# so we need to restrict the max usage to prevent DoS attack
|
||||
contract-query-gas-limit = "3000000"
|
||||
|
||||
# The flag to specify whether print contract logs or not
|
||||
contract-debug-mode = "false"
|
||||
|
||||
# The WASM VM memory cache size in MiB not bytes
|
||||
contract-memory-cache-size = "500"
|
||||
|
||||
contract-logging-whitelist = "*"
|
||||
# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries
|
||||
query_gas_limit = 300000
|
||||
# This is the number of wasm vm instances we keep cached in memory for speed-up
|
||||
# Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally
|
||||
lru_size = 0
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
|
||||
# TCP or UNIX socket address of the ABCI application,
|
||||
# or the name of an ABCI application compiled in with the Tendermint binary
|
||||
proxy_app = "tcp://127.0.0.1:26656"
|
||||
proxy_app = "tcp://127.0.0.1:26658"
|
||||
|
||||
# A custom human readable name for this node
|
||||
moniker = "localterra"
|
||||
|
@ -47,7 +47,7 @@ db_backend = "goleveldb"
|
|||
db_dir = "data"
|
||||
|
||||
# Output level for logging, including package level options
|
||||
log_level = "debug"
|
||||
log_level = "info"
|
||||
|
||||
# Output format: 'plain' (colored text) or 'json'
|
||||
log_format = "plain"
|
||||
|
@ -136,14 +136,41 @@ max_subscription_clients = 100
|
|||
# the estimated # maximum number of broadcast_tx_commit calls per block.
|
||||
max_subscriptions_per_client = 5
|
||||
|
||||
# Experimental parameter to specify the maximum number of events a node will
|
||||
# buffer, per subscription, before returning an error and closing the
|
||||
# subscription. Must be set to at least 100, but higher values will accommodate
|
||||
# higher event throughput rates (and will use more memory).
|
||||
experimental_subscription_buffer_size = 200
|
||||
|
||||
# Experimental parameter to specify the maximum number of RPC responses that
|
||||
# can be buffered per WebSocket client. If clients cannot read from the
|
||||
# WebSocket endpoint fast enough, they will be disconnected, so increasing this
|
||||
# parameter may reduce the chances of them being disconnected (but will cause
|
||||
# the node to use more memory).
|
||||
#
|
||||
# Must be at least the same as "experimental_subscription_buffer_size",
|
||||
# otherwise connections could be dropped unnecessarily. This value should
|
||||
# ideally be somewhat higher than "experimental_subscription_buffer_size" to
|
||||
# accommodate non-subscription-related RPC responses.
|
||||
experimental_websocket_write_buffer_size = 200
|
||||
|
||||
# If a WebSocket client cannot read fast enough, at present we may
|
||||
# silently drop events instead of generating an error or disconnecting the
|
||||
# client.
|
||||
#
|
||||
# Enabling this experimental parameter will cause the WebSocket connection to
|
||||
# be closed instead if it cannot read fast enough, allowing for greater
|
||||
# predictability in subscription behaviour.
|
||||
experimental_close_on_slow_client = false
|
||||
|
||||
# How long to wait for a tx to be committed during /broadcast_tx_commit.
|
||||
# WARNING: Using a value larger than 10s will result in increasing the
|
||||
# global HTTP write timeout, which applies to all connections and endpoints.
|
||||
# See https://github.com/tendermint/tendermint/issues/3435
|
||||
timeout_broadcast_tx_commit = "10s"
|
||||
timeout_broadcast_tx_commit = "30s"
|
||||
|
||||
# Maximum size of request body, in bytes
|
||||
max_body_bytes = 4194304
|
||||
max_body_bytes = 1000000
|
||||
|
||||
# Maximum size of request header, in bytes
|
||||
max_header_bytes = 1048576
|
||||
|
@ -172,12 +199,13 @@ pprof_laddr = "localhost:6060"
|
|||
[p2p]
|
||||
|
||||
# Address to listen for incoming connections
|
||||
laddr = "tcp://0.0.0.0:26660"
|
||||
laddr = "tcp://0.0.0.0:26656"
|
||||
|
||||
# Address to advertise to peers for them to dial
|
||||
# If empty, will use the same port as the laddr,
|
||||
# and will introspect on the listener or use UPnP
|
||||
# to figure out the address.
|
||||
# to figure out the address. ip and port are required
|
||||
# example: 159.89.10.97:26656
|
||||
external_address = ""
|
||||
|
||||
# Comma separated list of seed nodes to connect to
|
||||
|
@ -302,6 +330,13 @@ discovery_time = "15s"
|
|||
# Will create a new, randomly named directory within, and remove it when done.
|
||||
temp_dir = ""
|
||||
|
||||
# The timeout duration before re-requesting a chunk, possibly from a different
|
||||
# peer (default: 1 minute).
|
||||
chunk_request_timeout = "10s"
|
||||
|
||||
# The number of concurrent chunk fetchers to run (default: 1).
|
||||
chunk_fetchers = "4"
|
||||
|
||||
#######################################################
|
||||
### Fast Sync Configuration Connections ###
|
||||
#######################################################
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"genesis_time": "2021-05-26T10:02:06.396784Z",
|
||||
"genesis_time": "2022-05-16T04:54:32.922225Z",
|
||||
"chain_id": "localterra",
|
||||
"initial_height": "1",
|
||||
"consensus_params": {
|
||||
|
@ -14,9 +14,7 @@
|
|||
"max_bytes": "1048576"
|
||||
},
|
||||
"validator": {
|
||||
"pub_key_types": [
|
||||
"ed25519"
|
||||
]
|
||||
"pub_key_types": ["ed25519"]
|
||||
},
|
||||
"version": {}
|
||||
},
|
||||
|
@ -122,299 +120,107 @@
|
|||
{
|
||||
"address": "terra199vw7724lzkwz6lf2hsx04lrxfkz09tg8dlp6r",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra18wlvftxzj6zt0xugy2lr9nxzu402690ltaf4ss",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1dcegyrekltswvyy0xy69ydgxn9x8x32zdtapd8",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1e8ryd9ezefuucd4mje33zdms9m2s90m57878v9",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra17tv2hvwpg0ukqgd2y5ct2w54fyan7z0zxrm2f9",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1757tkx08n0cqrw7p86ny9lnxsqeth0wgp0em95",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra17lmam6zguazs5q5u6z5mmx76uj63gldnse2pdp",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"address": "terra1lkccuqgj6sjwjn8gsa9xlklqv4pmrqg9dx2fxc",
|
||||
"coins": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "1000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "1000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "10000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "10000000000000000"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"supply": [
|
||||
{
|
||||
"denom": "ueur",
|
||||
"amount": "110000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "ukrw",
|
||||
"amount": "11000000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uluna",
|
||||
"amount": "11000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "usdr",
|
||||
"amount": "110000000000000000"
|
||||
},
|
||||
{
|
||||
"denom": "uusd",
|
||||
"amount": "110000000000000000"
|
||||
}
|
||||
],
|
||||
"denom_metadata": []
|
||||
|
@ -548,10 +354,7 @@
|
|||
"clients_consensus": [],
|
||||
"clients_metadata": [],
|
||||
"params": {
|
||||
"allowed_clients": [
|
||||
"06-solomachine",
|
||||
"07-tendermint"
|
||||
]
|
||||
"allowed_clients": ["06-solomachine", "07-tendermint"]
|
||||
},
|
||||
"create_localhost": false,
|
||||
"next_client_sequence": "0"
|
||||
|
@ -572,13 +375,6 @@
|
|||
"next_channel_sequence": "0"
|
||||
}
|
||||
},
|
||||
"market": {
|
||||
"params": {
|
||||
"base_pool": "7000000000000.000000000000000000",
|
||||
"pool_recovery_period": "200",
|
||||
"min_stability_spread": "0.005000000000000000"
|
||||
}
|
||||
},
|
||||
"mint": {
|
||||
"minter": {
|
||||
"inflation": "0.130000000000000000",
|
||||
|
@ -586,48 +382,13 @@
|
|||
},
|
||||
"params": {
|
||||
"mint_denom": "uluna",
|
||||
"inflation_rate_change": "0.000000000000000000",
|
||||
"inflation_rate_change": "0.130000000000000000",
|
||||
"inflation_max": "0.200000000000000000",
|
||||
"inflation_min": "0.070000000000000000",
|
||||
"goal_bonded": "0.670000000000000000",
|
||||
"blocks_per_year": "6311520"
|
||||
}
|
||||
},
|
||||
"oracle": {
|
||||
"params": {
|
||||
"vote_period": "5",
|
||||
"vote_threshold": "0.500000000000000000",
|
||||
"reward_band": "0.020000000000000000",
|
||||
"reward_distribution_window": "5256000",
|
||||
"whitelist": [
|
||||
{
|
||||
"name": "ukrw",
|
||||
"tobin_tax": "0.002500000000000000"
|
||||
},
|
||||
{
|
||||
"name": "usdr",
|
||||
"tobin_tax": "0.002500000000000000"
|
||||
},
|
||||
{
|
||||
"name": "uusd",
|
||||
"tobin_tax": "0.002500000000000000"
|
||||
},
|
||||
{
|
||||
"name": "ueur",
|
||||
"tobin_tax": "0.002500000000000000"
|
||||
}
|
||||
],
|
||||
"slash_fraction": "0.000100000000000000",
|
||||
"slash_window": "100800",
|
||||
"min_valid_per_window": "0.050000000000000000"
|
||||
},
|
||||
"feeder_delegations": [],
|
||||
"exchange_rates": [],
|
||||
"miss_counters": [],
|
||||
"aggregate_exchange_rate_prevotes": [],
|
||||
"aggregate_exchange_rate_votes": [],
|
||||
"tobin_taxes": []
|
||||
},
|
||||
"params": null,
|
||||
"slashing": {
|
||||
"params": {
|
||||
|
@ -664,51 +425,20 @@
|
|||
"receive_enabled": true
|
||||
}
|
||||
},
|
||||
"treasury": {
|
||||
"params": {
|
||||
"tax_policy": {
|
||||
"rate_min": "0.000000000000000000",
|
||||
"rate_max": "0.000000000000000000",
|
||||
"cap": {
|
||||
"denom": "usdr",
|
||||
"amount": "0"
|
||||
},
|
||||
"change_rate_max": "0.000000000000000000"
|
||||
},
|
||||
"reward_policy": {
|
||||
"rate_min": "0.000000000000000000",
|
||||
"rate_max": "1.000000000000000000",
|
||||
"cap": {
|
||||
"denom": "unused",
|
||||
"amount": "0"
|
||||
},
|
||||
"change_rate_max": "0.000000000000000000"
|
||||
},
|
||||
"seigniorage_burden_target": "0.670000000000000000",
|
||||
"mining_increment": "1.070000000000000000",
|
||||
"window_short": "4",
|
||||
"window_long": "52",
|
||||
"window_probation": "12"
|
||||
},
|
||||
"tax_rate": "0.001000000000000000",
|
||||
"reward_weight": "0.050000000000000000",
|
||||
"tax_caps": [],
|
||||
"tax_proceeds": [],
|
||||
"epoch_initial_issuance": [],
|
||||
"epoch_states": []
|
||||
},
|
||||
"upgrade": {},
|
||||
"vesting": null,
|
||||
"wasm": {
|
||||
"params": {
|
||||
"max_contract_size": "614400",
|
||||
"max_contract_gas": "20000000",
|
||||
"max_contract_msg_size": "4096"
|
||||
"code_upload_access": {
|
||||
"permission": "Everybody",
|
||||
"address": ""
|
||||
},
|
||||
"instantiate_default_permission": "Everybody"
|
||||
},
|
||||
"last_code_id": "0",
|
||||
"last_instance_id": "0",
|
||||
"codes": [],
|
||||
"contracts": []
|
||||
"contracts": [],
|
||||
"sequences": [],
|
||||
"gen_msgs": []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
[alias]
|
||||
wasm = "build --release --target wasm32-unknown-unknown"
|
||||
wasm-debug = "build --target wasm32-unknown-unknown"
|
||||
schema = "run --example schema"
|
|
@ -1,19 +0,0 @@
|
|||
[package]
|
||||
name = "cw721"
|
||||
version = "0.10.1"
|
||||
authors = ["Ethan Frey <ethanfrey@users.noreply.github.com>"]
|
||||
edition = "2018"
|
||||
description = "Definition and types for the CosmWasm-721 NFT interface"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/CosmWasm/cw-nfts"
|
||||
homepage = "https://cosmwasm.com"
|
||||
documentation = "https://docs.cosmwasm.com"
|
||||
|
||||
[dependencies]
|
||||
cw0 = { version = "0.8.0" }
|
||||
cosmwasm-std = { version = "0.16.0" }
|
||||
schemars = "0.8.6"
|
||||
serde = { version = "1.0.130", default-features = false, features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cosmwasm-schema = { version = "1.0.0-beta2" }
|
|
@ -1,14 +0,0 @@
|
|||
CW721: A CosmWasm spec for non-fungible token contracts
|
||||
Copyright (C) 2020-2021 Confio OÜ
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License 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.
|
|
@ -1,122 +0,0 @@
|
|||
# CW721 Spec: Non Fungible Tokens
|
||||
|
||||
CW721 is a specification for non-fungible tokens based on CosmWasm.
|
||||
The name and design is based on Ethereum's ERC721 standard,
|
||||
with some enhancements. The types in here can be imported by
|
||||
contracts that wish to implement this spec, or by contracts that call
|
||||
to any standard cw721 contract.
|
||||
|
||||
The specification is split into multiple sections, a contract may only
|
||||
implement some of this functionality, but must implement the base.
|
||||
|
||||
## Base
|
||||
|
||||
This handles ownership, transfers, and allowances. These must be supported
|
||||
as is by all CW721 contracts. Note that all tokens must have an owner,
|
||||
as well as an ID. The ID is an arbitrary string, unique within the contract.
|
||||
|
||||
### Messages
|
||||
|
||||
`TransferNft{recipient, token_id}` -
|
||||
This transfers ownership of the token to `recipient` account. This is
|
||||
designed to send to an address controlled by a private key and *does not*
|
||||
trigger any actions on the recipient if it is a contract.
|
||||
|
||||
Requires `token_id` to point to a valid token, and `env.sender` to be
|
||||
the owner of it, or have an allowance to transfer it.
|
||||
|
||||
`SendNft{contract, token_id, msg}` -
|
||||
This transfers ownership of the token to `contract` account. `contract`
|
||||
must be an address controlled by a smart contract, which implements
|
||||
the CW721Receiver interface. The `msg` will be passed to the recipient
|
||||
contract, along with the token_id.
|
||||
|
||||
Requires `token_id` to point to a valid token, and `env.sender` to be
|
||||
the owner of it, or have an allowance to transfer it.
|
||||
|
||||
`Approve{spender, token_id, expires}` - Grants permission to `spender` to
|
||||
transfer or send the given token. This can only be performed when
|
||||
`env.sender` is the owner of the given `token_id` or an `operator`.
|
||||
There can multiple spender accounts per token, and they are cleared once
|
||||
the token is transfered or sent.
|
||||
|
||||
`Revoke{spender, token_id}` - This revokes a previously granted permission
|
||||
to transfer the given `token_id`. This can only be granted when
|
||||
`env.sender` is the owner of the given `token_id` or an `operator`.
|
||||
|
||||
`ApproveAll{operator, expires}` - Grant `operator` permission to transfer or send
|
||||
all tokens owned by `env.sender`. This approval is tied to the owner, not the
|
||||
tokens and applies to any future token that the owner receives as well.
|
||||
|
||||
`RevokeAll{operator}` - Revoke a previous `ApproveAll` permission granted
|
||||
to the given `operator`.
|
||||
|
||||
### Queries
|
||||
|
||||
`OwnerOf{token_id}` - Returns the owner of the given token,
|
||||
as well as anyone with approval on this particular token.
|
||||
If the token is unknown, returns an error. Return type is
|
||||
`OwnerResponse{owner}`.
|
||||
|
||||
`ApprovedForAll{owner, include_expired}` - List all operators that can
|
||||
access all of the owner's tokens. Return type is `ApprovedForAllResponse`.
|
||||
If `include_expired` is set, show expired owners in the results, otherwise,
|
||||
ignore them.
|
||||
|
||||
`NumTokens{}` - Total number of tokens issued
|
||||
|
||||
### Receiver
|
||||
|
||||
The counter-part to `SendNft` is `ReceiveNft`, which must be implemented by
|
||||
any contract that wishes to manage CW721 tokens. This is generally *not*
|
||||
implemented by any CW721 contract.
|
||||
|
||||
`ReceiveNft{sender, token_id, msg}` - This is designed to handle `SendNft`
|
||||
messages. The address of the contract is stored in `env.sender`
|
||||
so it cannot be faked. The contract should ensure the sender matches
|
||||
the token contract it expects to handle, and not allow arbitrary addresses.
|
||||
|
||||
The `sender` is the original account requesting to move the token
|
||||
and `msg` is a `Binary` data that can be decoded into a contract-specific
|
||||
message. This can be empty if we have only one default action,
|
||||
or it may be a `ReceiveMsg` variant to clarify the intention. For example,
|
||||
if I send to an exchange, I can specify the price I want to list the token
|
||||
for.
|
||||
|
||||
## Metadata
|
||||
|
||||
### Queries
|
||||
|
||||
`ContractInfo{}` - This returns top-level metadata about the contract.
|
||||
Namely, `name` and `symbol`.
|
||||
|
||||
`NftInfo{token_id}` - This returns metadata about one particular token.
|
||||
The return value is based on *ERC721 Metadata JSON Schema*, but directly
|
||||
from the contract, not as a Uri. Only the image link is a Uri.
|
||||
|
||||
`AllNftInfo{token_id}` - This returns the result of both `NftInfo`
|
||||
and `OwnerOf` as one query as an optimization for clients, which may
|
||||
want both info to display one NFT.
|
||||
|
||||
## Enumerable
|
||||
|
||||
### Queries
|
||||
|
||||
Pagination is acheived via `start_after` and `limit`. Limit is a request
|
||||
set by the client, if unset, the contract will automatically set it to
|
||||
`DefaultLimit` (suggested 10). If set, it will be used up to a `MaxLimit`
|
||||
value (suggested 30). Contracts can define other `DefaultLimit` and `MaxLimit`
|
||||
values without violating the CW721 spec, and clients should not rely on
|
||||
any particular values.
|
||||
|
||||
If `start_after` is unset, the query returns the first results, ordered by
|
||||
lexogaphically by `token_id`. If `start_after` is set, then it returns the
|
||||
first `limit` tokens *after* the given one. This allows straight-forward
|
||||
pagination by taking the last result returned (a `token_id`) and using it
|
||||
as the `start_after` value in a future query.
|
||||
|
||||
`Tokens{owner, start_after, limit}` - List all token_ids that belong to a given owner.
|
||||
Return type is `TokensResponse{tokens: Vec<token_id>}`.
|
||||
|
||||
`AllTokens{start_after, limit}` - Requires pagination. Lists all token_ids controlled by
|
||||
the contract.
|
|
@ -1,41 +0,0 @@
|
|||
use std::env::current_dir;
|
||||
use std::fs::create_dir_all;
|
||||
|
||||
use cosmwasm_schema::{export_schema, export_schema_with_title, remove_schemas, schema_for};
|
||||
use cosmwasm_std::Empty;
|
||||
|
||||
use cw721::{
|
||||
AllNftInfoResponse, ApprovalResponse, ApprovalsResponse, ContractInfoResponse, Cw721ExecuteMsg,
|
||||
Cw721QueryMsg, Cw721ReceiveMsg, NftInfoResponse, NumTokensResponse, OperatorsResponse,
|
||||
OwnerOfResponse, TokensResponse,
|
||||
};
|
||||
|
||||
type Extension = Option<Empty>;
|
||||
|
||||
fn main() {
|
||||
let mut out_dir = current_dir().unwrap();
|
||||
out_dir.push("schema");
|
||||
create_dir_all(&out_dir).unwrap();
|
||||
remove_schemas(&out_dir).unwrap();
|
||||
|
||||
export_schema(&schema_for!(Cw721ExecuteMsg), &out_dir);
|
||||
export_schema(&schema_for!(Cw721QueryMsg), &out_dir);
|
||||
export_schema(&schema_for!(Cw721ReceiveMsg), &out_dir);
|
||||
export_schema_with_title(
|
||||
&schema_for!(AllNftInfoResponse<Extension>),
|
||||
&out_dir,
|
||||
"AllNftInfoResponse",
|
||||
);
|
||||
export_schema(&schema_for!(ApprovalResponse), &out_dir);
|
||||
export_schema(&schema_for!(ApprovalsResponse), &out_dir);
|
||||
export_schema(&schema_for!(OperatorsResponse), &out_dir);
|
||||
export_schema(&schema_for!(ContractInfoResponse), &out_dir);
|
||||
export_schema(&schema_for!(OwnerOfResponse), &out_dir);
|
||||
export_schema_with_title(
|
||||
&schema_for!(NftInfoResponse<Extension>),
|
||||
&out_dir,
|
||||
"NftInfoResponse",
|
||||
);
|
||||
export_schema(&schema_for!(NumTokensResponse), &out_dir);
|
||||
export_schema(&schema_for!(TokensResponse), &out_dir);
|
||||
}
|
|
@ -1,155 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "AllNftInfoResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"access",
|
||||
"info"
|
||||
],
|
||||
"properties": {
|
||||
"access": {
|
||||
"description": "Who can transfer the token",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/OwnerOfResponse"
|
||||
}
|
||||
]
|
||||
},
|
||||
"info": {
|
||||
"description": "Data on the token itself,",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/NftInfoResponse_for_Nullable_Empty"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Empty": {
|
||||
"description": "An empty struct that serves as a placeholder in different places, such as contracts that don't set a custom message.\n\nIt is designed to be expressable in correct JSON and JSON Schema but contains no meaningful data. Previously we used enums without cases, but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451)",
|
||||
"type": "object"
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"NftInfoResponse_for_Nullable_Empty": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "You can add any custom metadata here when you extend cw721-base",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Empty"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"OwnerOfResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"description": "If set this address is approved to transfer/send the token as well",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"owner": {
|
||||
"description": "Owner of the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,94 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ApprovalResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approval"
|
||||
],
|
||||
"properties": {
|
||||
"approval": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ApprovalsResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "ContractInfoResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"symbol"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"symbol": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,236 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Cw721ExecuteMsg",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Transfer is a base message to move a token to another account without triggering actions",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"transfer_nft"
|
||||
],
|
||||
"properties": {
|
||||
"transfer_nft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"recipient",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"recipient": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Send is a base message to transfer a token to a contract and trigger an action on the receiving contract.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"send_nft"
|
||||
],
|
||||
"properties": {
|
||||
"send_nft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"contract",
|
||||
"msg",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"contract": {
|
||||
"type": "string"
|
||||
},
|
||||
"msg": {
|
||||
"$ref": "#/definitions/Binary"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Allows operator to transfer / send the token from the owner's account. If expiration is set, then this allowance has a time/height limit",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approve"
|
||||
],
|
||||
"properties": {
|
||||
"approve": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Remove previously granted Approval",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"revoke"
|
||||
],
|
||||
"properties": {
|
||||
"revoke": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"spender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"spender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Allows operator to transfer / send any token from the owner's account. If expiration is set, then this allowance has a time/height limit",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approve_all"
|
||||
],
|
||||
"properties": {
|
||||
"approve_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"operator": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Remove previously granted ApproveAll permission",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"revoke_all"
|
||||
],
|
||||
"properties": {
|
||||
"revoke_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator"
|
||||
],
|
||||
"properties": {
|
||||
"operator": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
],
|
||||
"definitions": {
|
||||
"Binary": {
|
||||
"description": "Binary is a wrapper around Vec<u8> to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec<u8>",
|
||||
"type": "string"
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,240 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Cw721QueryMsg",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Return the owner of the given token, error if token does not exist Return type: OwnerOfResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner_of"
|
||||
],
|
||||
"properties": {
|
||||
"owner_of": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Return operator that can access all of the owner's tokens. Return type: `ApprovedResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approved"
|
||||
],
|
||||
"properties": {
|
||||
"approved": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operator",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"operator": {
|
||||
"type": "string"
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "List all operators that can access all of the owner's tokens. Return type: `ApprovedForAllResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approved_for_all"
|
||||
],
|
||||
"properties": {
|
||||
"approved_for_all": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Total number of tokens issued",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"num_tokens"
|
||||
],
|
||||
"properties": {
|
||||
"num_tokens": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns top-level metadata about the contract: `ContractInfoResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"contract_info"
|
||||
],
|
||||
"properties": {
|
||||
"contract_info": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema* but directly from the contract: `NftInfoResponse`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"nft_info"
|
||||
],
|
||||
"properties": {
|
||||
"nft_info": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With MetaData Extension. Returns the result of both `NftInfo` and `OwnerOf` as one query as an optimization for clients: `AllNftInfo`",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_nft_info"
|
||||
],
|
||||
"properties": {
|
||||
"all_nft_info": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"include_expired": {
|
||||
"description": "unset or false will filter out expired approvals, you must set to true to see them",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With Enumerable extension. Returns all tokens owned by the given address, [] if unset. Return type: TokensResponse.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"tokens"
|
||||
],
|
||||
"properties": {
|
||||
"tokens": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"owner": {
|
||||
"type": "string"
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "With Enumerable extension. Requires pagination. Lists all token_ids controlled by the contract. Return type: TokensResponse.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"all_tokens"
|
||||
],
|
||||
"properties": {
|
||||
"all_tokens": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"limit": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"start_after": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
}
|
|
@ -1,28 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Cw721ReceiveMsg",
|
||||
"description": "Cw721ReceiveMsg should be de/serialized under `Receive()` variant in a ExecuteMsg",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"msg",
|
||||
"sender",
|
||||
"token_id"
|
||||
],
|
||||
"properties": {
|
||||
"msg": {
|
||||
"$ref": "#/definitions/Binary"
|
||||
},
|
||||
"sender": {
|
||||
"type": "string"
|
||||
},
|
||||
"token_id": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Binary": {
|
||||
"description": "Binary is a wrapper around Vec<u8> to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec<u8>",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NftInfoResponse",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extension": {
|
||||
"description": "You can add any custom metadata here when you extend cw721-base",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Empty"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"token_uri": {
|
||||
"description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Empty": {
|
||||
"description": "An empty struct that serves as a placeholder in different places, such as contracts that don't set a custom message.\n\nIt is designed to be expressable in correct JSON and JSON Schema but contains no meaningful data. Previously we used enums without cases, but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451)",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NumTokensResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"count"
|
||||
],
|
||||
"properties": {
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "OperatorsResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operators"
|
||||
],
|
||||
"properties": {
|
||||
"operators": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,103 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "OwnerOfResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"approvals",
|
||||
"owner"
|
||||
],
|
||||
"properties": {
|
||||
"approvals": {
|
||||
"description": "If set this address is approved to transfer/send the token as well",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Approval"
|
||||
}
|
||||
},
|
||||
"owner": {
|
||||
"description": "Owner of the token",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Approval": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"expires",
|
||||
"spender"
|
||||
],
|
||||
"properties": {
|
||||
"expires": {
|
||||
"description": "When the Approval expires (maybe Expiration::never)",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Expiration"
|
||||
}
|
||||
]
|
||||
},
|
||||
"spender": {
|
||||
"description": "Account that can transfer/send the token",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "AtHeight will expire when `env.block.height` >= height",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_height"
|
||||
],
|
||||
"properties": {
|
||||
"at_height": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "AtTime will expire when `env.block.time` >= time",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"at_time"
|
||||
],
|
||||
"properties": {
|
||||
"at_time": {
|
||||
"$ref": "#/definitions/Timestamp"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"description": "Never will never expire. Used to express the empty variant",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"never"
|
||||
],
|
||||
"properties": {
|
||||
"never": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Timestamp": {
|
||||
"description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Uint64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Uint64": {
|
||||
"description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "TokensResponse",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"tokens"
|
||||
],
|
||||
"properties": {
|
||||
"tokens": {
|
||||
"description": "Contains all token_ids in lexicographical ordering If there are more than `limit`, use `start_from` in future queries to achieve pagination.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
mod msg;
|
||||
mod query;
|
||||
mod receiver;
|
||||
mod traits;
|
||||
|
||||
pub use cw0::Expiration;
|
||||
|
||||
pub use crate::msg::Cw721ExecuteMsg;
|
||||
pub use crate::query::{
|
||||
AllNftInfoResponse, Approval, ApprovalResponse, ApprovalsResponse, ContractInfoResponse,
|
||||
Cw721QueryMsg, NftInfoResponse, NumTokensResponse, OperatorsResponse, OwnerOfResponse,
|
||||
TokensResponse,
|
||||
};
|
||||
pub use crate::receiver::Cw721ReceiveMsg;
|
||||
pub use crate::traits::{CustomMsg, Cw721, Cw721Execute, Cw721Query};
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue