Skip to content

Commit

Permalink
Respond to review feedback
Browse files Browse the repository at this point in the history
Signed-off-by: Sam Batschelet <[email protected]>
  • Loading branch information
hexfusion committed Oct 24, 2023
1 parent c4e6bb4 commit 19cedbc
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 39 deletions.
8 changes: 0 additions & 8 deletions x/programs/cmd/simulator/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ const (
)

type Plan struct {
// The name of the plan.
Name string `json,yaml:"name"`
// A description of the plan.
Description string `json,yaml:"description"`
// The key of the caller used in each step of the plan.
CallerKey string `yaml:"caller_key" json:"callerKey"`
// Steps to performed during simulation.
Expand Down Expand Up @@ -171,10 +167,6 @@ func validateAssertion(actual uint64, require *Require) (bool, error) {
return true, nil
}

if require.Result.Operator == "" {
return false, fmt.Errorf("missing assertion operator")
}

assertion := require.Result
// convert the assertion value(string) to uint64
value, err := strconv.ParseUint(assertion.Value, 10, 64)
Expand Down
28 changes: 23 additions & 5 deletions x/programs/cmd/simulator/cmd/plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,32 @@ func (c *runCmd) Verify() error {
if err != nil {
return err
}

// verify assertions
if step.Require != nil {
err = verifyAssertion(i, step.Require)
if err != nil {
return err
}
}
}

return nil
}

func verifyAssertion(i int, require *Require) error {
if require == nil {
return nil
}
if require.Result.Operator == "" {
return fmt.Errorf("%w %d: missing assertion operator", ErrInvalidStep, i)
}
if require.Result.Value == "" {
return fmt.Errorf("%w %d: missing assertion value", ErrInvalidStep, i)
}
return nil
}

func verifyEndpoint(i int, step *Step) error {
firstParamType := step.Params[0].Type

Expand All @@ -120,7 +141,7 @@ func verifyEndpoint(i int, step *Step) error {
return fmt.Errorf("%w %d %w: expected ed25519 or secp256k1", ErrInvalidStep, i, ErrInvalidParamType)
}
case EndpointReadOnly:
// verify the first param is an program id
// verify the first param is a program ID
if firstParamType != ID {
return fmt.Errorf("%w %d %w: %s", ErrInvalidStep, i, ErrInvalidParamType, ErrFirstParamRequiredID)
}
Expand Down Expand Up @@ -202,7 +223,6 @@ func runStepFunc(
} else if err != nil {
return err
}

resp.setMsg(fmt.Sprintf("created named key with address %s", utils.Address(key)))

return nil
Expand All @@ -214,7 +234,6 @@ func runStepFunc(
if err != nil {
return err
}

resp.setTxID(id.String())
resp.setTimestamp(time.Now().Unix())

Expand All @@ -229,12 +248,11 @@ func runStepFunc(

return nil
case EndpointReadOnly:
// TODO: implement readonly for now just qdon't charge for gas
// TODO: implement readonly for now just don't charge for gas
_, response, _, err := programExecuteFunc(ctx, log, db, params, method, math.MaxUint64)
if err != nil {
return err
}

resp.setResponse(response)
ok, err := validateAssertion(response[0], require)
if !ok {
Expand Down
2 changes: 1 addition & 1 deletion x/programs/cmd/simulator/cmd/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func programExecuteFunc(
return ids.Empty, nil, 0, err
}

// get balance
// get remaining balance from runtime meter
balance := programExecuteAction.GetBalance()

return programTxID, result, balance, nil
Expand Down
1 change: 0 additions & 1 deletion x/programs/rust/examples/token/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ serde ={ version = "1.0.130", features = ["derive"] }
[dev-dependencies]
serde_json = "1.0.68"


[lib]
crate-type = ["cdylib"] # set the crate(needed for cargo build to work properly)

Expand Down
10 changes: 5 additions & 5 deletions x/programs/rust/examples/token/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ This repository contains a simple example of a HyperSDK token program written in
## Overview
The token program provides the following features:

- Initialization of a token with a fixed supply.
- Ability to transfer tokens between accounts.
- Query balance of an account.
- Mint coins to an address.
- Initialization of a token with a fixed supply
- Ability to transfer tokens between accounts
- Query balance of an account
- Mint coins to an address

## Testing
HyperSDK programs can be tested with the VM simulator. To run our simulation
tests first compile the simulator binary which requires the latest version of
tests, first compile the simulator binary which requires the latest version of
golang. Review the source code of the `test_token_plan` located in `lib.rs` and
use it as a template to build your own tests.

Expand Down
5 changes: 5 additions & 0 deletions x/programs/rust/examples/token/scripts/build_and_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ simulator_bin="${simulator_path}"/bin/simulator
echo "Building Simulator..."
go build -o "${simulator_bin}" "${simulator_path}"/simulator.go

# Set environment variables for the test

# The path to the simulator binary
export SIMULATOR_PATH="${simulator_bin}"

# The path to the compiled Wasm program to be tested
export PROGRAM_PATH="../../../examples/testdata/token.wasm"

echo "Running Simulator Tests..."
Expand Down
25 changes: 6 additions & 19 deletions x/programs/rust/examples/token/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,22 +113,9 @@ pub fn get_balance(program: Program, recipient: Address) -> i64 {
mod tests {
use std::env;

use serde::{Deserialize, Serialize};
use wasmlanche_sdk::simulator::{Operator, Require, ResultAssertion};
#[derive(Debug, Serialize, Deserialize)]
struct PlanResponse {
id: u32,
result: PlanResult,
error: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct PlanResult {
id: Option<String>,
msg: Option<String>,
timestamp: u64,
response: Option<Vec<u64>>,
}
use wasmlanche_sdk::simulator::{
id_from_step, Operator, PlanResponse, Require, ResultAssertion,
};

// export SIMULATOR_PATH=/path/to/simulator
// export PROGRAM_PATH=/path/to/program.wasm
Expand Down Expand Up @@ -183,7 +170,7 @@ mod tests {
endpoint: Endpoint::Execute,
method: "init".into(),
// program was created in step 0 so we can reference its id using the step_N identifier
params: vec![Param::new(ParamType::Id, "step_0")],
params: vec![Param::new(ParamType::Id, id_from_step(0).as_ref())],
max_units: 10000,
require: None,
});
Expand All @@ -193,7 +180,7 @@ mod tests {
endpoint: Endpoint::Execute,
method: "mint_to".into(),
params: vec![
Param::new(ParamType::Id, "step_0"),
Param::new(ParamType::Id, id_from_step(0).as_ref()),
Param::new(ParamType::Key(Key::Ed25519), "alice_key"),
Param::new(ParamType::U64, "1000"),
],
Expand All @@ -206,7 +193,7 @@ mod tests {
endpoint: Endpoint::Execute,
method: "transfer".into(),
params: vec![
Param::new(ParamType::Id, "step_0"),
Param::new(ParamType::Id, id_from_step(0).as_ref()),
Param::new(ParamType::Key(Key::Ed25519), "alice_key"),
Param::new(ParamType::Key(Key::Ed25519), "bob_key"),
Param::new(ParamType::U64, "100"),
Expand Down
28 changes: 28 additions & 0 deletions x/programs/rust/wasmlanche_sdk/src/simulator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ pub const PATH_KEY: &str = "SIMULATOR_PATH";

use serde::{Deserialize, Serialize};

/// Converts the step index to a string identifier. This is used to populate Ids
/// created in previous plan steps.
pub fn id_from_step(i: usize) -> String {
format!("step_{}", i)
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Endpoint {
Expand Down Expand Up @@ -130,6 +136,28 @@ impl Plan {
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PlanResponse {
/// The numeric id of the step.
pub id: u32,
/// The result of the plan.
pub result: PlanResult,
/// An optional error message.
pub error: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PlanResult {
/// The ID created from the program execution.
pub id: Option<String>,
/// An optional message.
pub msg: Option<String>,
/// The timestamp of the function call response.
pub timestamp: u64,
/// The result of the function call.
pub response: Option<Vec<u64>>,
}

pub struct Client<P> {
/// Path to the simulator binary
path: P,
Expand Down

0 comments on commit 19cedbc

Please sign in to comment.