Skip to content

Commit

Permalink
Access to init args (#19)
Browse files Browse the repository at this point in the history
* __init_args

* clippy

* bump version

* update governance.did

Co-authored-by: Yan Chen <yan.chen@dfinity.org>
  • Loading branch information
chenyan2002 and chenyan-dfinity authored Jan 27, 2022
1 parent b671cd5 commit b48b279
Show file tree
Hide file tree
Showing 9 changed files with 381 additions and 267 deletions.
539 changes: 287 additions & 252 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ic-repl"
version = "0.1.1"
version = "0.1.2"
authors = ["DFINITY Team"]
edition = "2018"

Expand All @@ -18,7 +18,7 @@ codespan-reporting = "0.11"
pretty = "0.10.0"
pem = "0.8"
shellexpand = "2.1"
ic-agent = "0.9.0"
ic-agent = "0.11.0"
tokio = { version = "1.6.0", features = ["full"] }
garcon = "0.2.3"
anyhow = "1.0"
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ ic-repl [--replica [local|ic|url] | --offline [--format [ascii|png]]] --config <
| file <text> // load external file as a blob value
| fail <exp> // convert error message as text
| call (as <name>)? <name> . <name> ( <exp>,* ) // call a canister method, and store the result as a single value
| encode (<name> . <name>)? ( <exp>,* ) // encode candid arguments as a blob value
| encode (<name> . <name>)? ( <exp>,* ) // encode candid arguments as a blob value. canister.__init_args represents init args
| decode (as <name> . <name>)? <exp> // decode blob as candid values
| <id> ( <exp>,* ) // function application
<var> :=
Expand Down Expand Up @@ -181,7 +181,7 @@ If you are writing your own `.did` file, you can also supply the did file via th

## Issues

* Acess to service init type
* Acess to service init type (get from either Wasm or http endpoint)
* `IDLValue::Blob` for efficient blob serialization
* Autocompletion within Candid value
* Robust support for `~=`, requires inferring principal types
Expand Down
1 change: 1 addition & 0 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub enum Command {
body: Vec<Command>,
},
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone)]
pub enum BinOp {
Equal,
Expand Down
10 changes: 9 additions & 1 deletion src/exp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,15 @@ fn get_type(
let agent = &helper.agent;
let mut map = helper.canister_map.borrow_mut();
let info = map.get(agent, &canister_id).ok()?;
let func = info.methods.get(method)?.clone();
let func = if method == "__init_args" {
Function {
args: info.init.as_ref().unwrap_or(&Vec::new()).clone(),
rets: Vec::new(),
modes: Vec::new(),
}
} else {
info.methods.get(method)?.clone()
};
Some((info.env.clone(), func))
}
impl Method {
Expand Down
69 changes: 64 additions & 5 deletions src/governance.did
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
type AccountIdentifier = record { hash : vec nat8 };
type Action = variant {
RegisterKnownNeuron : KnownNeuron;
ManageNeuron : ManageNeuron;
ExecuteNnsFunction : ExecuteNnsFunction;
RewardNodeProvider : RewardNodeProvider;
Expand Down Expand Up @@ -36,6 +37,7 @@ type Command = variant {
ClaimOrRefresh : ClaimOrRefresh;
Configure : Configure;
RegisterVote : RegisterVote;
Merge : Merge;
DisburseToNeuron : DisburseToNeuron;
MakeProposal : Proposal;
MergeMaturity : MergeMaturity;
Expand All @@ -49,6 +51,7 @@ type Command_1 = variant {
ClaimOrRefresh : ClaimOrRefreshResponse;
Configure : record {};
RegisterVote : record {};
Merge : record {};
DisburseToNeuron : SpawnResponse;
MakeProposal : MakeProposalResponse;
MergeMaturity : MergeMaturityResponse;
Expand All @@ -57,6 +60,8 @@ type Command_1 = variant {
type Command_2 = variant {
Spawn : Spawn;
Split : Split;
Configure : Configure;
Merge : Merge;
DisburseToNeuron : DisburseToNeuron;
ClaimOrRefreshNeuron : ClaimOrRefresh;
MergeMaturity : MergeMaturity;
Expand Down Expand Up @@ -85,6 +90,7 @@ type Followees = record { followees : vec NeuronId };
type Governance = record {
default_followees : vec record { int32; Followees };
wait_for_quiet_threshold_seconds : nat64;
metrics : opt GovernanceCachedMetrics;
node_providers : vec NodeProvider;
economics : opt NetworkEconomics;
latest_reward_event : opt RewardEvent;
Expand All @@ -95,10 +101,34 @@ type Governance = record {
neurons : vec record { nat64; Neuron };
genesis_timestamp_seconds : nat64;
};
type GovernanceCachedMetrics = record {
not_dissolving_neurons_e8s_buckets : vec record { nat64; float64 };
garbage_collectable_neurons_count : nat64;
neurons_with_invalid_stake_count : nat64;
not_dissolving_neurons_count_buckets : vec record { nat64; nat64 };
total_supply_icp : nat64;
neurons_with_less_than_6_months_dissolve_delay_count : nat64;
dissolved_neurons_count : nat64;
total_staked_e8s : nat64;
not_dissolving_neurons_count : nat64;
dissolved_neurons_e8s : nat64;
neurons_with_less_than_6_months_dissolve_delay_e8s : nat64;
dissolving_neurons_count_buckets : vec record { nat64; nat64 };
dissolving_neurons_count : nat64;
dissolving_neurons_e8s_buckets : vec record { nat64; float64 };
community_fund_total_staked_e8s : nat64;
timestamp_seconds : nat64;
};
type GovernanceError = record { error_message : text; error_type : int32 };
type IncreaseDissolveDelay = record {
additional_dissolve_delay_seconds : nat32;
};
type KnownNeuron = record {
id : opt NeuronId;
known_neuron_data : opt KnownNeuronData;
};
type KnownNeuronData = record { name : text; description : opt text };
type ListKnownNeuronsResponse = record { known_neurons : vec KnownNeuron };
type ListNeurons = record {
neuron_ids : vec nat64;
include_neurons_readable_by_caller : bool;
Expand All @@ -122,6 +152,7 @@ type ManageNeuron = record {
neuron_id_or_subaccount : opt NeuronIdOrSubaccount;
};
type ManageNeuronResponse = record { command : opt Command_1 };
type Merge = record { source_neuron_id : opt NeuronId };
type MergeMaturity = record { percentage_to_merge : nat32 };
type MergeMaturityResponse = record {
merged_maturity_e8s : nat64;
Expand Down Expand Up @@ -150,10 +181,12 @@ type Neuron = record {
aging_since_timestamp_seconds : nat64;
hot_keys : vec principal;
account : vec nat8;
joined_community_fund_timestamp_seconds : opt nat64;
dissolve_state : opt DissolveState;
followees : vec record { int32; Followees };
neuron_fees_e8s : nat64;
transfer : opt NeuronStakeTransfer;
known_neuron_data : opt KnownNeuronData;
};
type NeuronId = record { id : nat64 };
type NeuronIdOrSubaccount = variant {
Expand All @@ -169,7 +202,10 @@ type NeuronInfo = record {
recent_ballots : vec BallotInfo;
created_timestamp_seconds : nat64;
state : int32;
stake_e8s : nat64;
joined_community_fund_timestamp_seconds : opt nat64;
retrieved_at_timestamp_seconds : nat64;
known_neuron_data : opt KnownNeuronData;
voting_power : nat64;
age_seconds : nat64;
};
Expand All @@ -182,16 +218,25 @@ type NeuronStakeTransfer = record {
transfer_timestamp : nat64;
block_height : nat64;
};
type NodeProvider = record { id : opt principal };
type NodeProvider = record {
id : opt principal;
reward_account : opt AccountIdentifier;
};
type Operation = variant {
RemoveHotKey : RemoveHotKey;
AddHotKey : AddHotKey;
StopDissolving : record {};
StartDissolving : record {};
IncreaseDissolveDelay : IncreaseDissolveDelay;
JoinCommunityFund : record {};
SetDissolveTimestamp : SetDissolveTimestamp;
};
type Proposal = record { url : text; action : opt Action; summary : text };
type Proposal = record {
url : text;
title : opt text;
action : opt Action;
summary : text;
};
type ProposalData = record {
id : opt NeuronId;
failure_reason : opt GovernanceError;
Expand All @@ -204,6 +249,7 @@ type ProposalData = record {
decided_timestamp_seconds : nat64;
proposal : opt Proposal;
proposer : opt NeuronId;
wait_for_quiet_state : opt WaitForQuietState;
executed_timestamp_seconds : nat64;
};
type ProposalInfo = record {
Expand All @@ -214,6 +260,7 @@ type ProposalInfo = record {
ballots : vec record { nat64; Ballot };
proposal_timestamp_seconds : nat64;
reward_event_round : nat64;
deadline_timestamp_seconds : opt nat64;
failed_timestamp_seconds : nat64;
reject_cost_e8s : nat64;
latest_tally : opt Tally;
Expand All @@ -228,7 +275,8 @@ type RemoveHotKey = record { hot_key_to_remove : opt principal };
type Result = variant { Ok; Err : GovernanceError };
type Result_1 = variant { Error : GovernanceError; NeuronId : NeuronId };
type Result_2 = variant { Ok : Neuron; Err : GovernanceError };
type Result_3 = variant { Ok : NeuronInfo; Err : GovernanceError };
type Result_3 = variant { Ok : RewardNodeProviders; Err : GovernanceError };
type Result_4 = variant { Ok : NeuronInfo; Err : GovernanceError };
type RewardEvent = record {
day_after_genesis : nat64;
actual_timestamp_seconds : nat64;
Expand All @@ -251,7 +299,7 @@ type SetDefaultFollowees = record {
default_followees : vec record { int32; Followees };
};
type SetDissolveTimestamp = record { dissolve_timestamp_seconds : nat64 };
type Spawn = record { new_controller : opt principal };
type Spawn = record { new_controller : opt principal; nonce : opt nat64 };
type SpawnResponse = record { created_neuron_id : opt NeuronId };
type Split = record { amount_e8s : nat64 };
type Tally = record {
Expand All @@ -260,18 +308,29 @@ type Tally = record {
total : nat64;
timestamp_seconds : nat64;
};
type UpdateNodeProvider = record { reward_account : opt AccountIdentifier };
type WaitForQuietState = record { current_deadline_timestamp_seconds : nat64 };
service : (Governance) -> {
claim_gtc_neurons : (principal, vec NeuronId) -> (Result);
claim_or_refresh_neuron_from_account : (ClaimOrRefreshNeuronFromAccount) -> (
ClaimOrRefreshNeuronFromAccountResponse,
);
get_full_neuron : (nat64) -> (Result_2) query;
get_full_neuron_by_id_or_subaccount : (NeuronIdOrSubaccount) -> (
Result_2,
) query;
get_monthly_node_provider_rewards : () -> (Result_3);
get_neuron_ids : () -> (vec nat64) query;
get_neuron_info : (nat64) -> (Result_3) query;
get_neuron_info : (nat64) -> (Result_4) query;
get_neuron_info_by_id_or_subaccount : (NeuronIdOrSubaccount) -> (
Result_4,
) query;
get_pending_proposals : () -> (vec ProposalInfo) query;
get_proposal_info : (nat64) -> (opt ProposalInfo) query;
list_known_neurons : () -> (ListKnownNeuronsResponse) query;
list_neurons : (ListNeurons) -> (ListNeuronsResponse) query;
list_proposals : (ListProposalInfo) -> (ListProposalInfoResponse) query;
manage_neuron : (ManageNeuron) -> (ManageNeuronResponse);
transfer_gtc_neuron : (NeuronId, NeuronId) -> (Result);
update_node_provider : (UpdateNodeProvider) -> (Result) query;
}
12 changes: 11 additions & 1 deletion src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub struct FuncEnv(pub BTreeMap<String, (Vec<String>, Vec<crate::command::Comman
pub struct CanisterInfo {
pub env: TypeEnv,
pub methods: BTreeMap<String, Function>,
pub init: Option<Vec<Type>>,
}
#[derive(Clone)]
pub enum OfflineOutput {
Expand Down Expand Up @@ -423,7 +424,16 @@ pub fn did_to_canister_info(name: &str, did: &str) -> anyhow::Result<CanisterInf
(meth.to_owned(), func.clone())
})
.collect();
Ok(CanisterInfo { env, methods })
let init = find_init_args(&env, &actor);
Ok(CanisterInfo { env, methods, init })
}

fn find_init_args(env: &TypeEnv, actor: &Type) -> Option<Vec<Type>> {
match actor {
Type::Var(id) => find_init_args(env, env.find_type(id).ok()?),
Type::Class(init, _) => Some(init.to_vec()),
_ => None,
}
}

#[test]
Expand Down
8 changes: 4 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ fn repl(opts: Opts) -> anyhow::Result<()> {
}
if let Some(file) = opts.script {
let cmd = Command::Load(file);
let mut helper = rl.helper_mut().unwrap();
return cmd.run(&mut helper);
let helper = rl.helper_mut().unwrap();
return cmd.run(helper);
}

let mut count = 1;
Expand All @@ -86,9 +86,9 @@ fn repl(opts: Opts) -> anyhow::Result<()> {
Ok(line) => {
rl.add_history_entry(&line);
unwrap(pretty_parse::<Command>("stdin", &line), |cmd| {
let mut helper = rl.helper_mut().unwrap();
let helper = rl.helper_mut().unwrap();
helper.history.push(line.clone());
unwrap(cmd.run(&mut helper), |_| {});
unwrap(cmd.run(helper), |_| {});
});
}
Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break,
Expand Down
1 change: 1 addition & 0 deletions src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ enum Comment {
Start,
}

#[allow(clippy::enum_variant_names)]
#[derive(Logos, Debug, Clone, PartialEq, Eq)]
enum Text {
#[error]
Expand Down

0 comments on commit b48b279

Please sign in to comment.