Skip to content

Commit

Permalink
🔧 Fix KV Errors (#236)
Browse files Browse the repository at this point in the history
* 🔧 Fix KV Delete Bug

* 🔨 Build KvMap

* 🔨 Add Keys and KvMap Functions

* 🔧 Fix Unit Tests

* 🔧 Fix Linting Issues in UnitTest

* chore: Set to boolean

* 🔨 Add Push0 Opcode

* 🔨 Add Invalid Opcode

* 🔧 Fix CODECOPY opcode

* 🔧 Fix Kv Get Functionality

* 🔧 Fix Linting Errors

* 🔧 Fix Linting Errors

* 🔧 Fix Napi Binding

---------

Co-authored-by: andreespirela <[email protected]>
  • Loading branch information
Roaring30s and andreespirela authored Oct 20, 2023
1 parent 6faa281 commit cdbc27c
Show file tree
Hide file tree
Showing 9 changed files with 419 additions and 270 deletions.
568 changes: 316 additions & 252 deletions crates/evm/lib.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/executor/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub fn get_execution_context(
ExmContext {
requests: HashMap::new(),
kv: HashMap::new(),
//data: Data::new(),
}
}
}
Expand Down
13 changes: 8 additions & 5 deletions crates/exm/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,17 @@

requests = {};

instantiated = false;
data = {
instantiated: false
}


constructor() {
}

init() {
if(!this.instantiated) {
this.instantiated = true;
if(!this.data.instantiated) {
this.data.instantiated = true;
}
}

Expand Down Expand Up @@ -256,11 +259,11 @@
const isEXM = Deno.core.opSync("op_get_executor_settings", "EXM");
const preKv = (globalThis?.exmContext?.kv || {});
// Inject KV for persistence
if(Object.values(preKv).length > 0 && !baseIns.instantiated) {
if(Object.values(preKv).length > 0 && !baseIns.data.instantiated) {
Object.entries(preKv).forEach(([key, val]) => {
baseIns.putKv(key, val);
});
baseIns.init();
baseIns.init();
}

if (!window[ExmSymbol]) {
Expand Down
13 changes: 13 additions & 0 deletions crates/exm/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,24 @@ pub struct DeterministicFetchBody {
pub headers: HashMap<String, String>,
pub vector: Vec<u8>,
}
#[derive(Deserialize, Serialize, Default, Clone)]
pub struct Data {
pub instantiated: bool,
}

impl Data {
pub fn new() -> Data {
Data {
instantiated: false,
}
}
}

#[derive(Deserialize, Serialize, Default, Clone)]
pub struct ExmContext {
pub requests: HashMap<String, DeterministicFetchBody>,
pub kv: HashMap<String, deno_core::serde_json::Value>,
//pub data: Data,
}

pub fn init(executor_settings: HashMap<String, Value>) -> Extension {
Expand Down
3 changes: 2 additions & 1 deletion crates/js/lib.rs

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion js/napi/napi.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,8 @@ export async function handle(state, action) {
requests: {},
kv: {
'PreviouslyAddedKey': 'Buccees'
}
},
data: {},
})
});
console.log(simulate);
Expand Down
49 changes: 44 additions & 5 deletions js/napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ mod tests {
// get_gateway(None, Some(false));
// get_cache();
// }

#[tokio::test]
pub async fn with_cache_test() {
get_gateway(None, None);
Expand Down Expand Up @@ -517,6 +517,7 @@ mod tests {
assert_eq!(contract.result.as_str().unwrap(), "Hello World");
assert_eq!(contract.updated, true);
}

//NOTE: Fix assert statements within _validateMintingFeeTest in ans.js
#[tokio::test]
pub async fn simulate_contract_ans() {
Expand All @@ -536,7 +537,7 @@ mod tests {
block: None,
input: serde_json::json!({"jwk_n":"iwLlbpT6b7rYOV6aJTTeSD5wXdqZYwYBGphdOclGeftR3wJcLp5OzWrQqexbfpvi-CBkxz0yroX4Of9Ikv_qoakIoz1qQsQztD2UR2MI6SAvbGPn8swKL7QId2OtyRtOJ3TAEuULt1lpA0nj67dOKNq-2HyhDyuCaZ6TTC2Luk5QUrqWKs9ix8xBNM_O20lmRGgDsrhNtTMca2tnkCk4JffGrEDVsF6iRM4Ls_KOcrAJlsrpSypi2M7O4rQkcyWaBerXomtkj4I5KBXnr5J9_sdLS-2esAHzpAr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820b889ad406142e5043dfd8d9ba6d9723fbef78a4c69ed294a65eb","mint_domain":"wearemintingyes", "function": "mint"})
.to_string(),
}],
}],
contract_init_state: Some(String::from(include_str!("../../../testdata/contracts/ans.json"))),
maybe_config: None,
maybe_cache: Some(false),
Expand All @@ -546,14 +547,13 @@ mod tests {
maybe_contract_source: Some(ContractSource {
contract_src: contract_source_vec.into(),
contract_type: SimulateContractType::JAVASCRIPT,
}),
}),
};

let contract = simulate_contract(execution_context).await.unwrap();

let contract_result = contract.state;
let str_state = contract_result.to_string();
//println!("{}", contract_result);
assert!(str_state.contains("wearemintingyes"));

}
Expand Down Expand Up @@ -677,7 +677,6 @@ mod tests {
assert_eq!(contract.exm_context.to_string().contains("Name"), true);
}


#[tokio::test]
pub async fn simulate_kv_del() {
let contract_source_bytes =
Expand Down Expand Up @@ -759,5 +758,45 @@ mod tests {
assert_eq!(contract.result, "[\"Yangtze\",\"Amazon\"]");
}

#[tokio::test]
pub async fn simulate_kv_get() {
let contract_source_bytes =
include_bytes!("../../../testdata/contracts/getKv.js");

let contract_source_vec = contract_source_bytes.to_vec();
let execution_context: SimulateExecutionContext =
SimulateExecutionContext {
contract_id: String::new(),
interactions: vec![SimulateInput {
id: String::from("abcd"),
owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"),
quantity: String::from("12301"),
reward: String::from("12931293"),
target: None,
tags: vec![],
block: None,
input: serde_json::json!({
"function": "get",
"key": "Yangtze"
})
.to_string(),
}],
contract_init_state: Some(r#"{"gets": [], "puts": []}"#.into()),

maybe_config: None,
maybe_cache: Some(false),
maybe_bundled_contract: None,
maybe_settings: None,
maybe_exm_context: Some(r#"{"requests": {}, "kv": {"Nile": "River1", "Yangtze": "River2", "Amazon": "River3", "Mississippi": "River4"}, "instantiated":false}"#.into()),
maybe_contract_source: Some(ContractSource {
contract_src: contract_source_vec.into(),
contract_type: SimulateContractType::JAVASCRIPT,
}),
};

let contract = simulate_contract(execution_context).await.unwrap();
assert_eq!(contract.state["gets"][0], "River2");
}

}

15 changes: 9 additions & 6 deletions testdata/contracts/ans.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@ export async function handle(state, action) {
const holders = state.balances.map((addr) => addr.address);

// !!!!Switch back to `_validateMintingFee` with fixes from the test deriv
await _validateMintingFeeTest(domain, txid, caller);

let t = await _validateMintingFeeTest(domain, txid, caller);

const domainColor = _generateDomainColor(domain);



if (!holders.includes(caller)) {

state.balances.push({
address: caller,
primary_domain: domain,
Expand All @@ -39,6 +42,7 @@ export async function handle(state, action) {
},
],
});

} else {
const callerIndex = _getValidateCallerIndex(caller);
state.balances[callerIndex].ownedDomains.push({
Expand Down Expand Up @@ -912,16 +916,15 @@ export async function handle(state, action) {
const domainType = _getDomainType(domain);
const domainUsdFee = state.pricing[domainType];
const arPrice = await _fetchArPrice();

const expectedPaidFee = domainUsdFee / arPrice; // fee in AR;
const everTx = await _getEverpayTx(txid, caller);

const paidAr = Number(everTx?.amount);
const feeConstant = state.isPublic ? 0.99 : 0.9; // 10% discount for WL mints

// !!!! switch out the numebrs for paidAr
ContractAssert(
1013417047999 >= Number((expectedPaidFee * feeConstant * 1e12).toFixed()),
1013417047999+4805402417 >= Number((expectedPaidFee * feeConstant * 1e12).toFixed()),
"ERROR_UNDERPAID"
);

Expand All @@ -947,7 +950,7 @@ export async function handle(state, action) {
const value = (hash >> (i * 8)) & 0xff;
color += ("00" + value.toString(16)).substr(-2);
}
return color;
return domain;
}

async function _isWhitelisted(address) {
Expand Down
24 changes: 24 additions & 0 deletions testdata/contracts/getKv.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export async function handle(state, action) {
const input = action.input;

if (input.function === "put") {
const { key, value } = input;
state.puts.push({ key, value }); // write to state
SmartWeave.kv.put(key, value); // write to KVS
return { result: JSON.stringify(SmartWeave.kv.getAll()) }; // state
}
if (input.function === "get") {
const { key } = input;

const res = SmartWeave.kv.get(key);
state.gets.push(res)
return { state };
}

if (input.function === "del") {
const { key } = input;
SmartWeave.kv.del(key);
return { state };
}
}

0 comments on commit cdbc27c

Please sign in to comment.