Skip to content

Commit

Permalink
Interact with contracts: upload, instantiate and call commands (#79)
Browse files Browse the repository at this point in the history
* WIP display all events

* Clean up and generalize displaying events

* Fix multiple event new lines

* Fmt

* Create wrapper types for Display, derive Debug for originals

* Control indentation of pretty printing

* Indent events display

* More tuning of runtime events pretty printing

* Fmt

* Use Display impls for printing events

* Add DisplayTransferEvent

* Namespace events

* Add CodeStored and Instantiated events

* Refactor Deploy command and use verbosity for events display

* Fix up string message return

* Code hash LowerHex and println after events

* Use LowerHex api for Bytes

* Parse code hash with 0x prefix

* Fmt

* Spawn canvas node for integration test

* Increment attempts

* Get the test running with spawned canvas node

* Instantiate deploy works with manual node

* Test works locally and cleans up temp dir

* Fmt

* Fix duplicate import

* Build before testing so cargo-contract bin available for testing

* Separate line for build

* Extract decode_hex util fn

* WIP failing Literal tests for SS58 account ids

* Upgrade to nom 0.6

* Use nom error in custom error, impl FromStr

* Fmt

* Update lockfile after merge

* Make TryFrom take reference for verbosity conversion

* Fix parsing literals

* Plumbing for custom encoders

* Implement AccountId32 custom encoder

* Refactor: extract env types

* Test for encoding ss58 literal

* Fmt and add back failing struct test

* Use AccountId type in test

* TEMP: Use github dependencies of scale-info and ink

* Err for 256 bit ints

* Use new registry type enumeration

* Extract type lookup and introduce Encoder

* WIP: extract Transcoder and implement env type decoding

* Implement env type decoding, removes generic Input.

Custom env decoders are trait objects so can't have generic type parameters on its decode method.

* Fix AccountId decoding, add some debug logging

* Test for different AccountId aliasing

* Passing tests for AccountId encoding and fmt

* Update scale-info and ink deps, patch ink deps for now

* Update scale-info and ink deps, patch ink deps for now

* Remove extrinsics feature

* Dependencies

* More deps

* Cargo.lock

* Cargo.lock

* WIP upgrading to latest subxt and scale-info

* More upgrading to latest subxt

* Fix more errors

* Fix up extrinsic commands

* Refactor transcoder decode, handle Compact

* Refactor transcoder encode, initial compact support

* Fmt

* Fix metadata file loading

* Constructor arg rename

* Enable tokio

* Make instantiate work

* Update contracts runtime from substrate-contracts-node

* Fix warnings and add todo

* Update subxt

* Add missing import

* Use explicit substrate branch to match subxt import

* Remove sp_rpc dependency

* Remove sp_rpc dependency

* Use metadata to decode events

* Fmt

* Pretty print events

* WIP custom transcoders for events

* Custom transcoders for events working

* Fix some warnings

* Slim down bat dependency

* Decode contract events

* Use correct field for instantiated contract account

* Fix warnings

* Fix multiple line warning

* Update contracts RPC types

* Fmt

* Fix deploy contract account

* Use ink! master branch

* Oops

* Remove patches

* Bump ink deps to rc6

* Update to latest subxt

* Update to latest subxt

* Fix errors after subxt update

* Fix instantiate_with_code.rs

* Update subxt

* Add deserializing context

* Fmt

* Expose public metadata fields

* Implement full metadata decoding

* Cargo.lock

* Update calls to work with storage_gas_limit from paritytech/substrate#10082

* Cargo.lock

* Update to latest subxt

* Fmt

* WIP unify instantiate command

* Fix call command errors

* Main warning unused result

* Call and instantiate warns and errors and fmt

* Update to ink rc7

* Default to local contract wasm if none specified

* Change instantiate endowment to value

* Use latest subxt branch

* Update to latest subxt

* Unify call and instantiate arg names

* Instantiate and call args consistency

* Add todo comment for encoding message args

* Refactor, tidy up call and instantiate

* Display decoded contract event separately

* Register env types with and without aliases

* Add pretty print flag

* WIP add upload

* Wiring up upload code extrinsic

* Download latest contracts node metadata

* Wire up upload command and WIP manifest path

* in! default features and cargo update

* Add manifest path argument for extrinsics

* Only fetch crate metadata once

* Fmt

* Cargo upgrade

* Update substrate dependencies

* Pretty print code upload dry run values

* Extract name value println macro

* Print code hash from upload extrinsic

* Refactor upload code command

* Pretty print instantiate results

* Add salt arg to instantiate command

* WIP custom events display, removes big bat dep

* Extract method for printing RPC contract result

* Ugly printing of events

* Fix contract event decoding

* Fmt

* Pretty print event fields

* Only print event fields if verbose

* More event prettification

* Fmt

* Resolve some todos

* Remove some code comments, moved to follow ups in PR

* Refactor: extract compact encoding function

* Fix storage_deposit_limit and add todo re: compact primitives

* Add todo re: compact primitives

* Cargo.lock

* Use released substrate crates and subxt master

* Fix encoding compact, inline for each uint

* Fix encoding compact, inline for each uint

* Add extrinsics markdown outline

* Dynamic compact encoding

* Replace bitvec todos with errs, added follow up in PR

* Remove todo about friendly encoding error, add to PR follow ups

* Rename codec to scale for test contract, fix some transcoding tests

* Attempt to fix linking with __ink_generate_metadata

* Update to ink rc8

* Add test for out of order composite fields

* Update ink metadata version

* Update ink metadata types and methods

* Fix metadata error message

* Add std feature to fix test compilation with inline contract

* Fix out of order struct fields

* Improve encoding of field error message

* Fmt imports

* Rename TypeLookupId to TypeLookup

* Remove alias matching for custom env type transcoding

* Fix variant encoding for maps and out of order fields

* Add failing test & impl for compact struct transcoding

* Use released version of pallet-contracts primitives

* WIP attempting to fix compact struct transcoding

* Fix compact struct decoding

* Add todo for integration test

* Renamed SconParseError

* Failing test for invalid integer

* Use nom-supreme for combinators, error handling

* Use released subxt

* Refactor integer parsing

* Refactor char parsing

* Refactor seq parsing

* Refactor tuple parsing

* Refactor unit tuple parsing

* Refactor map parsing

* Refactor bytes parsing

* Remove final nom `map` free function usage

* Use some postfix recognizes

* Remove final recognize combinator

* Use postfix value combinator

* Use opt postfix combinator

* Move entry point and top level parser to the top of the file

* Inline some string parsers

* Inline some local helper functions

* Fix failing integer tests

* Fix Rust ident parsing

* Fix up integration test

* Make clippy happy

* Fmt

* Clippy clippy clippy

* Ignore integration test for CI

* Support parsing underscore separators for integer literals

* + sign prefix parses to signed int

* Allow underscores for balance CLI args

* Add helper function for handling runtime errors

* Add helper function for displaying runtime module errors

* Elide lifetime

* Add some basic module level docs for transcoding

* Improve error message where metadata file not found

* Adding common args section to extrinsics.md

* Move --dry-run to extrinisic opts and more docs

* Move --storage-deposit-limit to ExtrinsicOpts, move ExtrinsicOpts to extrinsics.

* Add instantiate docs

* Add call docs

* Update Extrinsics docs

* Update Cargo.toml

Co-authored-by: Alexander Theißen <alex.theissen@me.com>

* Don't wait for finalization before displaying transaction success

* Update docs/extrinsics.md

Co-authored-by: Alexander Theißen <alex.theissen@me.com>

* Remove static error detail lookup, since it may be inaccurate if the target chain differs

* CLIPPY

* Print debug message lines

* Display not Debug return value

* Fmt

Co-authored-by: Alexander Theißen <alex.theissen@me.com>
  • Loading branch information
ascjones and athei authored Feb 16, 2022
1 parent 942c50c commit 4195197
Show file tree
Hide file tree
Showing 28 changed files with 5,870 additions and 1,684 deletions.
2,987 changes: 1,661 additions & 1,326 deletions Cargo.lock

Large diffs are not rendered by default.

49 changes: 34 additions & 15 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ heck = "0.4.0"
zip = { version = "0.5.13", default-features = false }
parity-wasm = "0.42.2"
cargo_metadata = "0.14.1"
codec = { package = "parity-scale-codec", version = "2.3.1", features = ["derive"] }
scale = { package = "parity-scale-codec", version = "2.3.1", features = ["derive"] }
which = "4.2.4"
colored = "2.0.0"
toml = "0.5.8"
Expand All @@ -43,14 +43,24 @@ url = { version = "2.2.2", features = ["serde"] }
impl-serde = "0.3.2"
regex = "1.5.4"

# dependencies for optional extrinsics feature
async-std = { version = "1.10.0", optional = true }
sp-core = { version = "2.0.1", optional = true }
subxt = { version = "0.14.0", package = "substrate-subxt", optional = true }
futures = { version = "0.3.21", optional = true }
hex = { version = "0.4.3", optional = true }

funty = "2.0.0"
# dependencies for extrinsics (deploying and calling a contract)
async-std = { version = "1.10.0", features = ["attributes", "tokio1"] }
ink_metadata = { version = "3.0.0-rc8", features = ["derive"] }
ink_env = "3.0.0-rc8"
scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
sp-core = "5.0.0"
sp-runtime = "5.0.0"
pallet-contracts-primitives = "5.0.0"
subxt = "0.17.0"
futures = "0.3.19"
hex = "0.4.3"
jsonrpsee = { version = "0.6.1", features = ["ws-client"] }
nom = "7.1.0"
nom-supreme = "0.6.0"
indexmap = "1.8.0"
thiserror = "1.0.30"
escape8259 = "0.5.1"
itertools = "0.10.3"

[build-dependencies]
anyhow = "1.0.53"
Expand All @@ -60,19 +70,28 @@ substrate-build-script-utils = "3.0.0"
platforms = "2.0.0"

[dev-dependencies]
assert_cmd = "2.0.4"
assert_matches = "1.5.0"
pretty_assertions = "1.1.0"
wabt = "0.10.0"
regex = "1.5.4"
predicates = "2.1.1"

[features]
default = []
ink_primitives = "3.0.0-rc8"
ink_storage = "3.0.0-rc8"
ink_lang = "3.0.0-rc8"

# Enable this for (experimental) commands to deploy, instantiate and call contracts.
#
# Disabled by default
extrinsics = ["sp-core", "subxt", "async-std", "futures", "hex"]
[features]
# This `std` feature is required for testing using an inline contract's metadata, because `ink!` annotates the metadata
# generation code with `#[cfg(feature = "std")]`.
default = ["std"]
std = []

# Enable this to execute long running tests, which usually are only run on the CI server
#
# Disabled by default
test-ci-only = []

# Enable this to execute tests which depend on a locally running contracts enabed chain
# e.g.https://github.com/paritytech/canvas-node
integration-tests = []
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ artifact to the `target/` directory.

Runs test suites defined for a smart contract off-chain.

##### `cargo contract upload`

Upload a contract to a `pallet-contracts` enabled chain. See [extrinsics](docs/extrinsics.md).

##### `cargo contract instantiate`

Create an instance of a contract on chain. See [extrinsics](docs/extrinsics.md).

##### `cargo contract call`

Invoke a message on an existing contract on chain. See [extrinsics](docs/extrinsics.md).

## License

The entire code within this repository is licensed under the [GPLv3](LICENSE).
Expand Down
103 changes: 103 additions & 0 deletions docs/extrinsics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Extrinsics
`cargo-contract` provides CLI support for uploading, instantiating and calling your contracts directly from the command
line.

## Common arguments

```
--suri
```
The Secret URI used for signing the extrinsic. For development chains, the well known endowed accounts can be used e.g.
`//Alice`. For other accounts, the actual secret key must be provided e.g. an `0x` prefixed 64 bit hex string, or the
seed phrase. See usage of [`subkey`](https://docs.substrate.io/v3/tools/subkey/) for examples, and docs for the expected
values in the [parsing code](https://docs.rs/sp-core/latest/sp_core/crypto/trait.Pair.html#method.from_string_with_seed).

:warning: **WARNING** :warning:

It is strongly recommended NOT to use secret keys from actual value bearing chains on the command line, since they are
visible on screen and are often saved to the command line shell's history. For now this tool should only be used for
development and testnets. It is a priority to implement a safer method of signing here before using this tool with value
bearing chains.

```
--password
```
*Optional*. The password for the `--suri`, see https://docs.substrate.io/v3/tools/subkey/#password-protected-keys.

```
--manifest-path
```
*Optional*. The path to the `Cargo.toml` of the contract crate. Use this to run commands on a contract from outside of
its project directory.

```
--url
```
*Optional*. The websockets url of an RPC node on the target chain. Defaults to a locally running node at
"ws://localhost:9944".

```
---dry-run
```
*Optional*. All extrinsic commands can be run without altering the chain state. Useful for testing if a command will be
successful, estimating gas costs or querying the result of `ink!` readonly messages.

```
--storage-deposit-limit
```
*Optional*. The maximum amount of balance that can be charged from the caller to pay for the storage consumed.

## Commands

### `upload`

Upload the Wasm code of the contract to the target chain. Invokes the [`upload_code`](https://github.com/paritytech/substrate/blob/master/frame/contracts/src/lib.rs#L509)
dispatchable.

e.g. `cargo contract upload --suri //Alice`

Assumes that `cargo contract build` has already been run to produce the contract artifacts.

### `instantiate`

Create an instance of a contract on chain. If the code has already been uploaded via `upload`, specify the resulting
`--code-hash` which will result in a call to [`instantiate`](https://github.com/paritytech/substrate/blob/master/frame/contracts/src/lib.rs#L460).
If no `--code-hash` is specified it will attempt to both upload the code and instantiate via the
[`instantiate_with_code`](https://github.com/paritytech/substrate/blob/master/frame/contracts/src/lib.rs#L419)
dispatchable.

e.g.
```
cargo contract instantiate \
--constructor new \
--args false \
--suri //Alice \
--code-hash 0xbc1b42256696c8a4187ec3ed79fc602789fc11287c4c30926f5e31ed8169574e
```
- `--constructor` the name of the contract constructor method to invoke.
- `--args` accepts a space separated list of values, encoded in order as the arguments of the constructor to invoke.
- `--code-hash` the hash of the uploaded code, returned from a call to `contract upload` or a previous
`contract instantiate`

### `call`

Invoke a message on an instance of a contract via the [`call`](https://github.com/paritytech/substrate/blob/master/frame/contracts/src/lib.rs#L359)
dispatchable.

e.g.
```
cargo contract call \
--contract 5FKy7RwXBCCACCEPjM5WugkhUd787FjdgieTkdj7TPngJzxN \
--message transfer \
--args 5FKy7RwXBCCACCEPjM5WugkhUd787FjdgieTkdj7TPngJzxN 1000 \
--suri //Alice
```

- `--contract` the account id of the contract to invoke, returned after a successful `contract instantiate`.
- `--message` the name of the contract message to invoke.
- `--args` accepts a space separated list of values, encoded in order as the arguments of the message to invoke.





111 changes: 0 additions & 111 deletions src/cmd/deploy.rs

This file was deleted.

Loading

0 comments on commit 4195197

Please sign in to comment.