|
| 1 | +use move_vm_types::natives::function::{NativeContext, NativeResult}; |
| 2 | +use move_vm_types::loaded_data::runtime_types::Type; |
| 3 | +use move_vm_types::values::Value; |
| 4 | +use libra_types::access_path::AccessPath; |
| 5 | +use libra_types::account_address::AccountAddress; |
| 6 | +use libra_types::vm_error::{VMStatus, StatusCode}; |
| 7 | +use libra_crypto::hash::{DefaultHasher, CryptoHasher}; |
| 8 | +use std::collections::VecDeque; |
| 9 | +use vm::errors::VMResult; |
| 10 | +use byteorder::{LittleEndian, ByteOrder}; |
| 11 | +use move_core_types::{ |
| 12 | + gas_schedule::{GasUnits, GasAlgebra}, |
| 13 | +}; |
| 14 | + |
| 15 | +const COST: u64 = 929; |
| 16 | +const PRICE_ORACLE_TAG: u8 = 255; |
| 17 | + |
| 18 | +pub fn native_oracle_get_price( |
| 19 | + context: &impl NativeContext, |
| 20 | + _ty_args: Vec<Type>, |
| 21 | + mut arguments: VecDeque<Value>, |
| 22 | +) -> VMResult<NativeResult> { |
| 23 | + if arguments.len() != 1 { |
| 24 | + let msg = format!( |
| 25 | + "wrong number of arguments for get_price expected 1 found {}", |
| 26 | + arguments.len() |
| 27 | + ); |
| 28 | + return Err(status(StatusCode::UNREACHABLE, &msg)); |
| 29 | + } |
| 30 | + |
| 31 | + let ticker = pop_arg!(arguments, u64); |
| 32 | + let price = |
| 33 | + make_path(ticker) |
| 34 | + .and_then(|path| { |
| 35 | + let value = context.raw_load(&path).map_err(|err| { |
| 36 | + status( |
| 37 | + StatusCode::STORAGE_ERROR, |
| 38 | + &format!("Failed to load ticker [{}]", err), |
| 39 | + ) |
| 40 | + })?; |
| 41 | + |
| 42 | + if let Some(price) = value { |
| 43 | + if price.len() != 8 { |
| 44 | + Err(status(StatusCode::TYPE_MISMATCH, "Invalid prise size")) |
| 45 | + } else { |
| 46 | + Ok(LittleEndian::read_u64(&price)) |
| 47 | + } |
| 48 | + } else { |
| 49 | + Err(status(StatusCode::STORAGE_ERROR, "Price is not found")) |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + let cost = GasUnits::new(COST); |
| 54 | + Ok(match price { |
| 55 | + Ok(price) => NativeResult::ok(cost, vec![Value::u64(price)]), |
| 56 | + Err(status) => NativeResult::err(cost, status), |
| 57 | + }) |
| 58 | +} |
| 59 | + |
| 60 | +fn status(code: StatusCode, msg: &str) -> VMStatus { |
| 61 | + VMStatus::new(code).with_message(msg.to_owned()) |
| 62 | +} |
| 63 | + |
| 64 | +pub fn make_path(ticker_pair: u64) -> Result<AccessPath, VMStatus> { |
| 65 | + let mut hasher = DefaultHasher::default(); |
| 66 | + let mut buf = [0; 8]; |
| 67 | + LittleEndian::write_u64(&mut buf, ticker_pair); |
| 68 | + hasher.write(&buf); |
| 69 | + let mut hash = hasher.finish().to_vec(); |
| 70 | + hash.insert(0, PRICE_ORACLE_TAG); |
| 71 | + Ok(AccessPath::new(AccountAddress::DEFAULT, hash)) |
| 72 | +} |
| 73 | + |
0 commit comments