Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A0-1610: Contract support redux #816

Merged
merged 21 commits into from
Dec 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/actions/run-e2e-test/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ inputs:
follow-up-finalization-check:
description: 'Whether to run a follow-up finalization check.'
required: false
deploy-adder:
description: 'Whether to deploy the adder sample contract to the node.'
required: false
default: 'false'

runs:
using: 'composite'
Expand Down Expand Up @@ -84,6 +88,14 @@ runs:
)
fi

DEPLOY_ADDER="${{ inputs.deploy-adder }}"

if [[ "${DEPLOY_ADDER}" = "true" ]]; then
pushd contracts/adder
export ADDER=$(./deploy.sh)
popd
fi

./.github/scripts/run_e2e_test.sh "${ARGS[@]}"

- name: Run finalization e2e test
Expand Down
7 changes: 6 additions & 1 deletion .github/scripts/run_e2e_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ if [[ -n "${ONLY_LEGACY:-}" ]]; then
ARGS+=(-e ONLY_LEGACY)
fi

docker run -v $(pwd)/docker/data:/data "${ARGS[@]}" aleph-e2e-client:latest
if [[ -n "${ADDER:-}" ]]; then
ARGS+=(-e "ADDER=${ADDER}")
ARGS+=(-e "ADDER_METADATA=/contracts/adder/target/ink/metadata.json")
fi

docker run -v "$(pwd)/contracts:/contracts" -v "$(pwd)/docker/data:/data" "${ARGS[@]}" aleph-e2e-client:latest

exit $?
8 changes: 2 additions & 6 deletions .github/workflows/check-excluded-packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,6 @@ jobs:
with:
version: '3.6.1'

- name: Install clippy and fmt
run: rustup component add clippy rustfmt

- name: Install WASM target
run: rustup target add wasm32-unknown-unknown

- name: Read excluded packages from Cargo.toml
id: read_excluded
uses: SebRollen/toml-action@v1.0.0
Expand Down Expand Up @@ -75,6 +69,8 @@ jobs:
do
echo "Checking package $p..."
pushd "$p"
rustup component add clippy rustfmt
rustup target add wasm32-unknown-unknown
cargo fmt --all --check
cargo clippy --all-features -- --no-deps -D warnings
popd
Expand Down
26 changes: 26 additions & 0 deletions .github/workflows/e2e-tests-main-devnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,31 @@ jobs:
UPGRADE_FINALIZATION_WAIT_SESSIONS: 2
timeout-minutes: 10

run-e2e-adder-contract-test:
needs: [build-test-docker, build-test-client]
name: Run e2e adder contract test
runs-on: ubuntu-20.04
steps:
- name: Checkout source code
uses: actions/checkout@v2

- name: Install cargo-contract
uses: baptiste0928/cargo-install@v1
with:
crate: cargo-contract
version: "2.0.0-beta.1"

- name: Install rust-src
working-directory: ./contracts
run: rustup component add rust-src

- name: Run e2e test
uses: ./.github/actions/run-e2e-test
with:
deploy-adder: true
test-case: adder
timeout-minutes: 10

# The tests below were written under the assumption that nonfinalized blocks are being produced, they need a rewrite before being reenabled.
# TODO(A0-1644): Reenable these tests.
# run-e2e-failing-version-upgrade:
Expand Down Expand Up @@ -659,6 +684,7 @@ jobs:
run-e2e-ban-threshold,
run-e2e-version-upgrade,
run-e2e-permissionless-ban,
run-e2e-adder-contract-test,
# run-e2e-failing-version-upgrade,
# run-e2e-version-upgrade-catchup,
]
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ exclude = [
"fork-off",
"benches/payout-stakers",
"bin/cliain",
"contracts/adder"
]

[profile.release]
Expand Down
4 changes: 3 additions & 1 deletion aleph-client/src/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,14 @@ impl SignedConnection {
if let Some(details) = tx.validation_details() {
info!(target:"aleph-client", "Sending extrinsic {}.{} with params: {:?}", details.pallet_name, details.call_name, params);
}

let progress = self
.connection
.client
.tx()
.sign_and_submit_then_watch(&tx, &self.signer, params)
.await?;
.await
.map_err(|e| anyhow!("Failed to submit transaction: {:?}", e))?;

// In case of Submitted hash does not mean anything
let hash = match status {
Expand Down
195 changes: 195 additions & 0 deletions aleph-client/src/contract/convertible_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
use std::{fmt::Debug, ops::Deref, str::FromStr};

use anyhow::{anyhow, bail, Context, Result};
use contract_transcode::Value;

use crate::AccountId;

/// Temporary wrapper for converting from [Value] to primitive types.
///
/// ```
/// # #![feature(assert_matches)]
/// # #![feature(type_ascription)]
/// # use std::assert_matches::assert_matches;
/// # use anyhow::{anyhow, Result};
/// # use aleph_client::{AccountId, contract::ConvertibleValue};
/// use contract_transcode::Value;
///
/// assert_matches!(ConvertibleValue(Value::UInt(42)).try_into(), Ok(42u128));
/// assert_matches!(ConvertibleValue(Value::UInt(42)).try_into(), Ok(42u32));
/// assert_matches!(ConvertibleValue(Value::UInt(u128::MAX)).try_into(): Result<u32>, Err(_));
/// assert_matches!(ConvertibleValue(Value::Bool(true)).try_into(), Ok(true));
/// assert_matches!(
/// ConvertibleValue(Value::Literal("5H8cjBBzCJrAvDn9LHZpzzJi2UKvEGC9VeVYzWX5TrwRyVCA".to_string())).
/// try_into(): Result<AccountId>,
/// Ok(_)
/// );
/// assert_matches!(
/// ConvertibleValue(Value::String("not a number".to_string())).try_into(): Result<u128>,
/// Err(_)
/// );
/// ```
#[derive(Debug, Clone)]
pub struct ConvertibleValue(pub Value);

impl Deref for ConvertibleValue {
type Target = Value;

fn deref(&self) -> &Value {
&self.0
}
}

impl TryFrom<ConvertibleValue> for bool {
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> Result<bool, Self::Error> {
match value.0 {
Value::Bool(value) => Ok(value),
_ => bail!("Expected {:?} to be a boolean", value.0),
}
}
}

impl TryFrom<ConvertibleValue> for u128 {
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> Result<u128, Self::Error> {
match value.0 {
Value::UInt(value) => Ok(value),
_ => bail!("Expected {:?} to be an integer", value.0),
}
}
}

impl TryFrom<ConvertibleValue> for u32 {
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> Result<u32, Self::Error> {
match value.0 {
Value::UInt(value) => Ok(value.try_into()?),
_ => bail!("Expected {:?} to be an integer", value.0),
}
}
}

impl TryFrom<ConvertibleValue> for AccountId {
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> Result<AccountId, Self::Error> {
match value.0 {
Value::Literal(value) => {
AccountId::from_str(&value).map_err(|_| anyhow!("Invalid account id"))
}
_ => bail!("Expected {:?} to be a string", value),
}
}
}

impl<T> TryFrom<ConvertibleValue> for Result<T>
where
ConvertibleValue: TryInto<T, Error = anyhow::Error>,
{
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> Result<Result<T>, Self::Error> {
if let Value::Tuple(tuple) = &value.0 {
match tuple.ident() {
Some(x) if x == "Ok" => {
if tuple.values().count() == 1 {
let item =
ConvertibleValue(tuple.values().next().unwrap().clone()).try_into()?;
return Ok(Ok(item));
} else {
bail!("Unexpected number of elements in Ok variant: {:?}", &value);
}
}
Some(x) if x == "Err" => {
if tuple.values().count() == 1 {
return Ok(Err(anyhow!(value.to_string())));
} else {
bail!("Unexpected number of elements in Err variant: {:?}", &value);
}
}
_ => (),
}
}

bail!("Expected {:?} to be an Ok(_) or Err(_) tuple.", value);
}
}
obrok marked this conversation as resolved.
Show resolved Hide resolved

impl TryFrom<ConvertibleValue> for String {
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> std::result::Result<String, Self::Error> {
let seq = match value.0 {
Value::Seq(seq) => seq,
_ => bail!("Failed parsing `ConvertibleValue` to `String`. Expected `Seq(Value::UInt)` but instead got: {:?}", value),
};

let mut bytes: Vec<u8> = Vec::with_capacity(seq.len());
for el in seq.elems() {
if let Value::UInt(byte) = *el {
if byte > u8::MAX as u128 {
bail!("Expected number <= u8::MAX but instead got: {:?}", byte)
}
bytes.push(byte as u8);
} else {
bail!("Failed parsing `ConvertibleValue` to `String`. Expected `Value::UInt` but instead got: {:?}", el);
}
}
String::from_utf8(bytes).context("Failed parsing bytes to UTF-8 String.")
}
}

auto trait NotEq {}
// We're basically telling the compiler that there is no instance of NotEq for `(X,X)` tuple.
// Or put differently - that you can't implement `NotEq` for `(X,X)`.
impl<X> !NotEq for (X, X) {}

impl<T> TryFrom<ConvertibleValue> for Option<T>
where
T: TryFrom<ConvertibleValue, Error = anyhow::Error> + Debug,
// We will derive this impl only when `T != ConvertibleValue`.
// Otherwise we will get a conflict with generic impl in the rust `core` crate.
(ConvertibleValue, T): NotEq,
{
type Error = anyhow::Error;

fn try_from(value: ConvertibleValue) -> std::result::Result<Option<T>, Self::Error> {
let tuple = match &value.0 {
Value::Tuple(tuple) => tuple,
_ => bail!("Expected {:?} to be a Some(_) or None Tuple.", &value),
};

match tuple.ident() {
Some(x) if x == "Some" => {
if tuple.values().count() == 1 {
let item =
ConvertibleValue(tuple.values().next().unwrap().clone()).try_into()?;
Ok(Some(item))
} else {
bail!(
"Unexpected number of elements in Some(_) variant: {:?}. Expected one.",
&value
);
}
}
Some(x) if x == "None" => {
if tuple.values().count() == 0 {
Ok(None)
} else {
bail!(
"Unexpected number of elements in None variant: {:?}. Expected zero.",
&value
);
}
}
_ => bail!(
"Expected `.ident()` to be `Some` or `None`, got: {:?}",
&tuple
),
}
}
}
Loading