diff --git a/Cargo.lock b/Cargo.lock index 818ab8431..4d115ed4d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,6 +1914,25 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "flow-client" +version = "0.1.0" +dependencies = [ + "gateway-crypto", + "hex", + "hex-buffer-serde", + "our-std", + "parity-scale-codec 2.1.1", + "serde", + "serde_json", + "sp-core", + "sp-io", + "sp-runtime", + "sp-runtime-interface", + "sp-std", + "types-derive", +] + [[package]] name = "fnv" version = "1.0.7" @@ -4759,6 +4778,7 @@ dependencies = [ "ethabi 12.0.0", "ethereum-client", "ethereum-types 0.11.0", + "flow-client", "frame-benchmarking", "frame-support", "frame-system", diff --git a/Cargo.toml b/Cargo.toml index 3256bb432..d889d6ded 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ 'our-std', 'gateway-crypto', 'ethereum-client', + 'flow-client', 'test-utils/open-oracle-mock-reporter', 'trx-request', 'types-derive', diff --git a/flow-client/Cargo.toml b/flow-client/Cargo.toml new file mode 100644 index 000000000..6a46ede20 --- /dev/null +++ b/flow-client/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = 'flow-client' +version = '0.1.0' +authors = ['Compound '] +edition = '2018' + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +codec = { package = 'parity-scale-codec', version = '2.0.0', default-features = false, features = ['derive'] } +hex = { version = '0.4.2', default-features = false } +hex-buffer-serde = { version = "0.3.0", default-features = false, features = ['alloc', 'const_len'] } +serde = { version = '1.0.125', features = ['derive'], default-features = false } +serde_json = { version = '1.0.64', features = ['alloc'], default-features = false } +sp-io = { default-features = false, features = ['disable_oom', 'disable_panic_handler'], git = 'https://github.com/compound-finance/substrate', branch = 'jflatow/compound'} +sp-core = { default-features = false, git = 'https://github.com/compound-finance/substrate', branch = 'jflatow/compound' } +sp-runtime = { default-features = false, git = 'https://github.com/compound-finance/substrate', branch = 'jflatow/compound' } +sp-runtime-interface = { default-features = false, git = 'https://github.com/compound-finance/substrate', branch = 'jflatow/compound' } +sp-std = { default-features = false, git = 'https://github.com/compound-finance/substrate', branch = 'jflatow/compound' } +our-std = { path = '../our-std', default-features = false } +types-derive = { path = '../types-derive' } +gateway-crypto = { path = '../gateway-crypto', default-features = false } + +[features] +default = ['std'] +std = [ + 'codec/std', + 'serde/std', + 'serde_json/std', + 'sp-core/std', + 'sp-io/std', + 'sp-runtime/std', + 'sp-runtime-interface/std', + 'sp-std/std', + 'our-std/std', + 'gateway-crypto/std', +] +runtime-debug = ['our-std/runtime-debug'] diff --git a/flow-client/src/events.rs b/flow-client/src/events.rs new file mode 100644 index 000000000..ad7b4f8e4 --- /dev/null +++ b/flow-client/src/events.rs @@ -0,0 +1,74 @@ +use codec::{Decode, Encode}; +use our_std::convert::TryInto; +use our_std::{Deserialize, RuntimeDebug, Serialize}; + +use types_derive::Types; + +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, Types, Serialize, Deserialize)] +struct Lock { + asset: String, + // sender: String, + recipient: String, + amount: u128, +} + +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, Types, Serialize, Deserialize)] +pub enum FlowEvent { + Lock { + asset: [u8; 8], + // sender: String, + recipient: [u8; 8], + amount: u128, + }, // NoticeInvoked { + // era_id: u32, + // era_index: u32, + // notice_hash: [u8; 32], + // result: Vec, + // } +} + +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)] +pub enum EventError { + UnknownEventTopic(String), + ErrorParsingData, +} + +pub fn decode_event(topic: &str, data: &str) -> Result { + match topic { + "Lock" => { + let event_res: serde_json::error::Result = serde_json::from_str(&data); + let event = event_res.map_err(|_| EventError::ErrorParsingData)?; + let asset_res = gateway_crypto::flow_asset_str_to_address(&event.asset); + + Ok(FlowEvent::Lock { + asset: asset_res.ok_or(EventError::ErrorParsingData)?, + // sender: event.sender, + recipient: hex::decode(event.recipient) + .map_err(|_| EventError::ErrorParsingData)? + .try_into() + .map_err(|_| EventError::ErrorParsingData)?, + amount: event.amount, + }) + } + _ => Err(EventError::UnknownEventTopic(topic.to_string())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_flow_decode_lock_event() { + let topic = "Lock"; + let data = "{\"asset\":\"FLOW\",\"recipient\":\"fc6346ab93540e97\",\"amount\":1000000000}"; + assert_eq!( + decode_event(topic, data), + Ok(FlowEvent::Lock { + asset: [70, 76, 79, 87, 0, 0, 0, 0], // "FLOW" asset + recipient: hex::decode("fc6346ab93540e97").unwrap().try_into().unwrap(), + amount: 1000000000 + }) + ) + } +} diff --git a/flow-client/src/lib.rs b/flow-client/src/lib.rs new file mode 100644 index 000000000..a2c3f2c84 --- /dev/null +++ b/flow-client/src/lib.rs @@ -0,0 +1,438 @@ +use codec::{Decode, Encode}; +use hex_buffer_serde::{ConstHex, ConstHexForm}; +use our_std::convert::TryInto; +use our_std::{debug, error, info, warn, Deserialize, RuntimeDebug, Serialize}; +use sp_runtime::offchain::{http, Duration}; +use sp_runtime_interface::pass_by::PassByCodec; +use types_derive::{type_alias, Types}; + +pub mod events; + +pub use crate::events::FlowEvent; + +#[type_alias] +pub type FlowBlockNumber = u64; + +#[type_alias] +pub type FlowHash = [u8; 32]; + +const FLOW_FETCH_DEADLINE: u64 = 10_000; + +#[derive(Serialize, Deserialize)] // used in config +#[derive(Clone, Eq, PartialEq, Encode, Decode, PassByCodec, RuntimeDebug, Types)] +#[allow(non_snake_case)] +pub struct FlowBlock { + #[serde(with = "ConstHexForm")] + pub blockId: FlowHash, + #[serde(with = "ConstHexForm")] + pub parentBlockId: FlowHash, + pub height: FlowBlockNumber, + #[serde(skip)] + pub events: Vec, +} + +#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, Types)] +pub enum FlowClientError { + DecodeError, + HttpIoError, + HttpTimeout, + HttpErrorCode(u16), + InvalidUTF8, + JsonParseError, + NoResult, + BadResponse, +} + +// #[derive(Deserialize, RuntimeDebug, PartialEq)] +// pub struct ResponseError { +// pub message: Option, +// pub code: Option, +// } + +#[derive(Clone, Deserialize, RuntimeDebug, PartialEq)] +#[allow(non_snake_case)] +pub struct LogObject { + blockId: Option, + blockHeight: Option, + transactionId: Option, + transactionIndex: Option, + eventIndex: Option, + topic: Option, + data: Option, +} + +#[derive(Deserialize, RuntimeDebug, PartialEq)] +pub struct GetLogsResponse { + pub result: Option>, + // pub error: Option, +} + +#[allow(non_snake_case)] +#[derive(Clone, Deserialize, RuntimeDebug, PartialEq)] +pub struct BlockObject { + pub blockId: Option, + pub parentBlockId: Option, + pub height: Option, + pub timestamp: Option, +} + +#[derive(Deserialize, RuntimeDebug, PartialEq)] +pub struct BlockResponse { + pub result: Option, + // pub error: Option, +} + +#[derive(Deserialize, RuntimeDebug, PartialEq)] +pub struct BlockNumberResponse { + pub result: Option, + // pub error: Option, +} + +fn deserialize_get_logs_response(response: &str) -> Result { + let result: serde_json::error::Result = serde_json::from_str(response); + Ok(result.map_err(|_| FlowClientError::BadResponse)?) +} + +// TODO think about error field and introducing back parse_error method +fn deserialize_get_block_by_number_response( + response: &str, +) -> Result { + let result: serde_json::error::Result = serde_json::from_str(response); + Ok(result.map_err(|_| FlowClientError::BadResponse)?) +} + +fn deserialize_block_number_response( + response: &str, +) -> Result { + let result: serde_json::error::Result = serde_json::from_str(response); + Ok(result.map_err(|_| FlowClientError::BadResponse)?) +} + +// TODO think about optional data here??? +pub fn send_request(server: &str, path: &str, data: &str) -> Result { + let deadline = sp_io::offchain::timestamp().add(Duration::from_millis(FLOW_FETCH_DEADLINE)); + let request_url = format!("{}/{}", server, path); + + debug!("Request {}, with data {}", request_url, data); + + let request = http::Request::post(&request_url, vec![data.to_string()]); + + let pending = request + .deadline(deadline) + .add_header("Content-Type", "application/json") + .send() + .map_err(|_| FlowClientError::HttpIoError)?; + + let response = pending + .try_wait(deadline) + .map_err(|_| FlowClientError::HttpTimeout)? + .map_err(|_| FlowClientError::HttpTimeout)?; + + if response.code != 200 { + warn!("Unexpected status code: {}", response.code); + return Err(FlowClientError::HttpErrorCode(response.code)); + } + + let body = response.body().collect::>(); + + // Create a str slice from the body. + let body_str = sp_std::str::from_utf8(&body).map_err(|_| { + warn!("No UTF8 body"); + FlowClientError::InvalidUTF8 + })?; + debug!("Request Response: {}", body_str.clone()); + + Ok(String::from(body_str)) +} + +pub fn get_block( + server: &str, + flow_starport_address: &str, + block_num: FlowBlockNumber, + topic: &str, // Lock +) -> Result { + debug!( + "flow_starport_address: {:X?}, block_num {:?}, topic {:?}", + flow_starport_address, block_num, topic + ); + let block_obj = get_block_object(server, block_num)?; + let get_logs_params = serde_json::json!({ + "topic": format!("A.{}.Starport.{}", flow_starport_address, topic), + "startHeight": block_num, + "endHeight": block_num, + }); + debug!("get_logs_params: {:?}", get_logs_params.clone()); + let get_logs_response_str: String = + send_request(server, "events", &get_logs_params.to_string())?; + let get_logs_response = deserialize_get_logs_response(&get_logs_response_str)?; + let event_objects = get_logs_response + .result + .ok_or_else(|| FlowClientError::BadResponse)?; + + if event_objects.len() > 0 { + info!( + "Found {} events @ Flow Starport {}", + event_objects.len(), + flow_starport_address + ); + } + + let mut events = Vec::with_capacity(event_objects.len()); + for ev_obj in event_objects { + let data = ev_obj.data.ok_or_else(|| FlowClientError::BadResponse)?; + match events::decode_event(topic, &data) { + Ok(event) => events.push(event), + Err(events::EventError::UnknownEventTopic(topic)) => { + warn!("Skipping unrecognized topic {:?}", topic) + } + Err(err) => { + error!("Failed to decode {:?}", err); + return Err(FlowClientError::DecodeError); + } + } + } + + Ok(FlowBlock { + blockId: hex::decode(block_obj.blockId.ok_or(FlowClientError::DecodeError)?) + .map_err(|_| FlowClientError::DecodeError)? + .try_into() + .map_err(|_| FlowClientError::DecodeError)?, + parentBlockId: hex::decode( + block_obj + .parentBlockId + .ok_or(FlowClientError::DecodeError)?, + ) + .map_err(|_| FlowClientError::DecodeError)? + .try_into() + .map_err(|_| FlowClientError::DecodeError)?, + height: block_obj.height.ok_or(FlowClientError::DecodeError)?, + events, + }) +} + +pub fn get_block_object( + server: &str, + block_num: FlowBlockNumber, +) -> Result { + let get_block_params = serde_json::json!({ + "height": block_num, + }); + let response_str: String = send_request(server, "block", &get_block_params.to_string())?; + debug!("get block object {}", response_str); + let response = deserialize_get_block_by_number_response(&response_str)?; + response.result.ok_or(FlowClientError::NoResult) +} + +pub fn get_latest_block_number(server: &str) -> Result { + let response_str: String = send_request(server, "latest_block_number", "{}")?; + let response = deserialize_block_number_response(&response_str)?; + debug!("eth_blockNumber response: {:?}", response.result.clone()); + Ok(response.result.ok_or(FlowClientError::NoResult)?) +} + +// TODO add error tests +#[cfg(test)] +mod tests { + use crate::*; + + use sp_core::offchain::{testing, OffchainDbExt, OffchainWorkerExt}; + + #[test] + fn test_flow_get_block() { + let (offchain, state) = testing::TestOffchainExt::new(); + let mut t = sp_io::TestExternalities::default(); + t.register_extension(OffchainDbExt::new(offchain.clone())); + t.register_extension(OffchainWorkerExt::new(offchain)); + { + let mut s = state.write(); + s.expect_request( + testing::PendingRequest { + method: "POST".into(), + uri: "https://mainnet-flow-fetcher/block".into(), + headers: vec![("Content-Type".to_owned(), "application/json".to_owned())], + body: br#"{"height":34944396}"#.to_vec(), + response: Some(br#"{"result":{"blockId":"4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289","parentBlockId":"35afa24cc7ea92585b11a4e220c8226b5613556c8deb9f24d008acbdcf24c80d","height":34944396,"timestamp":"2021-06-09 21:16:57.510218679 +0000 UTC"}}"#.to_vec()), + sent: true, + ..Default::default() + }); + s.expect_request( + testing::PendingRequest { + method: "POST".into(), + uri: "https://mainnet-flow-fetcher/events".into(), + headers: vec![("Content-Type".to_owned(), "application/json".to_owned())], + body: br#"{"topic":"A.c8873a26b148ed14.Starport.Lock","startHeight":34944396,"endHeight":34944396}"#.to_vec(), + response: Some(br#"{"result":[{"blockId":"4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289","blockHeight":34944396,"transactionId":"f4d331583dd5ddc1e57e72ca02197d7ff365bde7b2ca9f3114d8c44d248d1c6c","transactionIndex":0,"eventIndex":2,"topic":"A.c8873a26b148ed14.Starport.Lock","data":"{\"asset\":\"FLOW\",\"recipient\":\"fc6346ab93540e97\",\"amount\":1000000000}"}]}"#.to_vec()), + sent: true, + ..Default::default() + }); + } + t.execute_with(|| { + let result = get_block( + "https://mainnet-flow-fetcher", + "c8873a26b148ed14", // Starport address + 34944396, + "Lock", + ); + let block = result.unwrap(); + let blockId_res: FlowHash = + hex::decode("4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289") + .unwrap() + .try_into() + .unwrap(); + let parentBlockId_res: FlowHash = + hex::decode("35afa24cc7ea92585b11a4e220c8226b5613556c8deb9f24d008acbdcf24c80d") + .unwrap() + .try_into() + .unwrap(); + assert_eq!(block.blockId, blockId_res); + assert_eq!(block.parentBlockId, parentBlockId_res); + assert_eq!(block.height, 34944396); + + assert_eq!( + block.events, + vec![FlowEvent::Lock { + asset: [70, 76, 79, 87, 0, 0, 0, 0], // FLOW asset + recipient: hex::decode("fc6346ab93540e97").unwrap().try_into().unwrap(), + amount: 1000000000 + }] + ); + }); + } + + #[test] + fn test_flow_get_latest_block_number() { + let (offchain, state) = testing::TestOffchainExt::new(); + let mut t = sp_io::TestExternalities::default(); + t.register_extension(OffchainDbExt::new(offchain.clone())); + t.register_extension(OffchainWorkerExt::new(offchain)); + { + let mut s = state.write(); + s.expect_request(testing::PendingRequest { + method: "POST".into(), + uri: "https://mainnet-flow-fetcher/latest_block_number".into(), + headers: vec![("Content-Type".to_owned(), "application/json".to_owned())], + body: br#"{}"#.to_vec(), + response: Some(br#"{"result": 35705489}"#.to_vec()), + sent: true, + ..Default::default() + }); + } + t.execute_with(|| { + let result = get_latest_block_number("https://mainnet-flow-fetcher"); + assert_eq!(result, Ok(35705489)); + }); + } + + #[test] + fn test_flow_get_block_object() { + let (offchain, state) = testing::TestOffchainExt::new(); + let mut t = sp_io::TestExternalities::default(); + t.register_extension(OffchainDbExt::new(offchain.clone())); + t.register_extension(OffchainWorkerExt::new(offchain)); + { + let mut s = state.write(); + s.expect_request( + testing::PendingRequest { + method: "POST".into(), + uri: "https://mainnet-flow-fetcher/block".into(), + headers: vec![("Content-Type".to_owned(), "application/json".to_owned())], + body: br#"{"height":34944396}"#.to_vec(), + response: Some(br#"{"result":{"blockId":"4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289","parentBlockId":"35afa24cc7ea92585b11a4e220c8226b5613556c8deb9f24d008acbdcf24c80d","height":34944396,"timestamp":"2021-06-09 21:16:57.510218679 +0000 UTC"}}"#.to_vec()), + sent: true, + ..Default::default() + }); + } + t.execute_with(|| { + let result = get_block_object("https://mainnet-flow-fetcher", 34944396); + let block = result.unwrap(); + assert_eq!( + block.blockId, + Some("4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289".into()) + ); + assert_eq!( + block.parentBlockId, + Some("35afa24cc7ea92585b11a4e220c8226b5613556c8deb9f24d008acbdcf24c80d".into()) + ); + assert_eq!(block.height, Some(34944396)); + assert_eq!( + block.timestamp, + Some("2021-06-09 21:16:57.510218679 +0000 UTC".into()) + ); + }); + } + + #[test] + fn test_flow_deserialize_get_logs_response() { + const RESPONSE: &str = r#"{ + "result":[ + { + "blockId":"4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289", + "blockHeight":34944396, + "transactionId":"f4d331583dd5ddc1e57e72ca02197d7ff365bde7b2ca9f3114d8c44d248d1c6c", + "transactionIndex":0, + "eventIndex":2, + "topic":"A.c8873a26b148ed14.Starport.Lock", + "data":"{\"asset\":\"FLOW\",\"recipient\":\"fc6346ab93540e97\",\"amount\":1000000000}" + } + ] + }"#; + let result = deserialize_get_logs_response(RESPONSE); + let expected = GetLogsResponse { + result: Some(vec![LogObject { + blockId: Some(String::from( + "4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289", + )), + blockHeight: Some(34944396), + transactionId: Some(String::from( + "f4d331583dd5ddc1e57e72ca02197d7ff365bde7b2ca9f3114d8c44d248d1c6c", + )), + transactionIndex: Some(0), + eventIndex: Some(2), + topic: Some(String::from("A.c8873a26b148ed14.Starport.Lock")), + data: Some(String::from( + "{\"asset\":\"FLOW\",\"recipient\":\"fc6346ab93540e97\",\"amount\":1000000000}", + )), + }]), + // error: None, + }; + assert_eq!(result.unwrap(), expected) + } + + #[test] + fn test_flow_deserialize_get_block_by_number_response() { + const RESPONSE: &str = r#"{ + "result":{ + "blockId":"4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289", + "parentBlockId":"35afa24cc7ea92585b11a4e220c8226b5613556c8deb9f24d008acbdcf24c80d", + "height":34944396, + "timestamp":"2021-06-09 21:16:57.510218679 +0000 UTC" + } + }"#; + let result = deserialize_get_block_by_number_response(RESPONSE); + let expected = BlockResponse { + result: Some(BlockObject { + blockId: Some(String::from( + "4ac2583773d9d3e994e76ac2432f6a3b3641410894c5ff7616f6ce244b35b289", + )), + parentBlockId: Some(String::from( + "35afa24cc7ea92585b11a4e220c8226b5613556c8deb9f24d008acbdcf24c80d", + )), + height: Some(34944396), + timestamp: Some(String::from("2021-06-09 21:16:57.510218679 +0000 UTC")), + }), + // error: None, + }; + assert_eq!(result.unwrap(), expected) + } + + #[test] + fn test_flow_deserialize_block_number_response() { + const RESPONSE: &str = r#"{"result": 35705489}"#; + let result = deserialize_block_number_response(RESPONSE); + let expected = BlockNumberResponse { + result: Some(35705489), + // error: None, + }; + assert_eq!(result.unwrap(), expected) + } +} diff --git a/flow/.gitignore b/flow/.gitignore new file mode 100644 index 000000000..931e2da09 --- /dev/null +++ b/flow/.gitignore @@ -0,0 +1,4 @@ +test/node_modules +test/flow.json +test/package-lock.json +test/yarn.lock diff --git a/flow/cadence/contracts/Starport.cdc b/flow/cadence/contracts/Starport.cdc new file mode 100644 index 000000000..1e438d2af --- /dev/null +++ b/flow/cadence/contracts/Starport.cdc @@ -0,0 +1,384 @@ +// import FlowToken from 0x0ae53cb6e3f42a79 +// import FungibleToken from 0xee82856bf20e2aa6 + +import FungibleToken from 0x9a0766d93b6608b7 +import FlowToken from 0x7e60df042a9c0868 + +import Crypto + +pub contract Starport { + + // Event that is emitted when Flow tokens are locked in the Starport vault + //event Lock(address indexed asset, address indexed sender, string chain, bytes32 indexed recipient, uint amount); + pub event Lock(asset: String, recipient: Address?, amount: UFix64) + + // Event that is emitted when tokens are unlocked by Gateway + pub event Unlock(account: Address, amount: UFix64, asset: String) + + // Event that is emitted when a set of authorities is changed + pub event ChangeAuthorities(newAuthorities: [String]) + + // Event that is emitted when new supply cap for an asset is set + pub event NewSupplyCap(asset: String, supplyCap: UFix64) + + // Event that is emitted when locked Flow tokens are withdrawn + pub event TokensWithdrawn(asset: String, amount: UFix64) + + // Event that is emitted when notice is incorrect + pub event NoticeError(noticeEraId: UInt256, noticeEraIndex: UInt256, error: String) + + // Private vault with public deposit function + access(self) var vault: @FlowToken.Vault + + // TODO Find a way to store Starport keylist when it's available + access(self) var authorities: [String] + + access(self) var eraId: UInt256 + + access(self) var invokedNotices: [String] + + access(self) var unlockHex: String + + access(self) var changeAuthoritiesHex: String + + access(self) var setSupplyCapHex: String + + access(self) var flowAssetHex: String + + access(self) var supplyCaps: {String: UFix64} + + /// This interface for locking Flow tokens. + pub resource interface FlowLock { + pub fun lock(from: @FungibleToken.Vault) + } + + pub resource StarportParticipant: FlowLock { + + pub fun lock(from: @FungibleToken.Vault) { + pre { + // Starport.vault.balance <= Starport.supplyCaps["FLOW"]: "Supply Cap Exceeded" + Starport.vault.balance + from.balance <= Starport.getFlowSupplyCap(): "Supply Cap Exceeded" + } + let from <- from as! @FlowToken.Vault + let balance = from.balance + Starport.vault.deposit(from: <-from) + emit Lock(asset: "FLOW", recipient: self.owner?.address, amount: balance); + } + } + + pub resource Administrator { + // withdraw + // TODO - delete it later? + // Allows the administrator to withdraw locked Flow tokens + pub fun withdrawLockedFlowTokens(amount: UFix64): @FungibleToken.Vault { + let vault <- Starport.vault.withdraw(amount: amount) + emit TokensWithdrawn(asset: "FLOW", amount: amount) + return <-vault + } + + // Unlock + // + // Allows the administrator to unlock Flow tokens + pub fun unlock(toAddress: Address, amount: UFix64) { + // Get capability to deposit tokens to `toAddress` receiver + let toAddressReceiver = getAccount(toAddress) + .getCapability<&FlowToken.Vault{FungibleToken.Receiver}>(/public/flowTokenReceiver)! + .borrow() ?? panic("Could not borrow FLOW receiver capability") + + // Withdraw Flow tokens to the temporary vault + let temporaryVault <- Starport.vault.withdraw(amount: amount) + + // Deposit Flow tokens to receiver from the temporary vault + toAddressReceiver.deposit(from: <-temporaryVault) + + // Emit event + emit Unlock(account: toAddress, amount: amount, asset: "FLOW") + } + + pub fun changeAuthorities(newAuthorities: [String]) { + pre { + newAuthorities.length > 0: "New authority set can not be empty" + } + Starport.authorities = newAuthorities + + emit ChangeAuthorities(newAuthorities: newAuthorities) + } + + pub fun setSupplyCap(supplyCap: UFix64) { + emit NewSupplyCap(asset: "FLOW", supplyCap: supplyCap); + + Starport.supplyCaps["FLOW"] = supplyCap; + } + } + + pub fun createStarportParticipant(): @StarportParticipant { + return <- create StarportParticipant() + } + + pub fun getLockedBalance(): UFix64 { + return self.vault.balance + } + + pub fun getAuthorities(): [String] { + return self.authorities + } + + pub fun getEraId(): UInt256 { + return self.eraId + } + + pub fun getFlowSupplyCap(): UFix64 { + return self.supplyCaps["FLOW"] ?? UFix64(0) + } + + // Unlock Flow tokens with notice + pub fun unlock(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + toAddress: Address, + amount: UFix64, + signatures: [String]) { + // Build `unlock` notice message + let message = self.buildUnlockMessage(noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + parentNoticeHex: parentNoticeHex, + toAddress: toAddress, + amount: amount) + + // Validate notice's signatures, invocation status and era ids + if !self.isValidNotice(noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + message: message, + signatures: signatures) { + log("Invalid Notice") + return + } + + // Get capability to deposit tokens to `toAddress` receiver + let toAddressReceiver = getAccount(toAddress) + .getCapability<&FlowToken.Vault{FungibleToken.Receiver}>(/public/flowTokenReceiver)! + .borrow() ?? panic("Could not borrow FLOW receiver capability") + + // Withdraw Flow tokens to the temporary vault + let temporaryVault <- Starport.vault.withdraw(amount: amount) + + emit TokensWithdrawn(asset: "FLOW", amount: amount) + + // Deposit Flow tokens to receiver from the temporary vault + toAddressReceiver.deposit(from: <-temporaryVault) + + // Emit event + emit Unlock(account: toAddress, amount: amount, asset: "FLOW") + } + + pub fun buildUnlockMessage(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + toAddress: Address, + amount: UFix64): [UInt8] { + let message = self.unlockHex.decodeHex() + .concat(noticeEraId.toBigEndianBytes()) + .concat(noticeEraIndex.toBigEndianBytes()) + .concat(parentNoticeHex.decodeHex()) + .concat(toAddress.toBytes()) + .concat(amount.toBigEndianBytes()) + return message + } + + access(self) fun buildNoticeHash(noticeEraId: UInt256, noticeEraIndex: UInt256): String { + return noticeEraId.toString().concat("_").concat(noticeEraIndex.toString()) + } + + access(self) fun checkNoticeSignerAuthorized(message: [UInt8], signatures: [String]): Bool { + let authoritiesList: [Crypto.KeyList] = [] + + for authority in Starport.authorities { + let keylist = Crypto.KeyList() + let publicKey = PublicKey( + publicKey: authority.decodeHex(), + signatureAlgorithm: SignatureAlgorithm.ECDSA_secp256k1 + ) + + keylist.add( + publicKey, + hashAlgorithm: HashAlgorithm.SHA3_256, + weight: 1.0 // Check weight, think about value here + ) + authoritiesList.append(keylist) + } + + let validSigs: [Int] = [] + for signature in signatures { + let signatureSet: [Crypto.KeyListSignature] = [] + signatureSet.append( + Crypto.KeyListSignature( + keyIndex: 0, + signature: signature.decodeHex() + ) + ) + + var i = 0 + for keyList in authoritiesList { + if keyList.verify(signatureSet: signatureSet, signedData: message) { + if !validSigs.contains(i) { + validSigs.append(i) + break + } + } + i = i + 1 + } + } + + return validSigs.length >= self.getQuorum(authorityCount: self.authorities.length) + } + + access(self) fun getQuorum(authorityCount: Int): Int { + return (authorityCount / 3) + 1 + } + + // Validates notice's signatures, invocation status and era ids + // @note Side effects: notice invocation status and eraId storage values can be changed + access(self) fun isValidNotice(noticeEraId: UInt256, + noticeEraIndex: UInt256, + message: [UInt8], + signatures: [String]): Bool { + // Check validity of signatures for the notice + let isSigValid = self.checkNoticeSignerAuthorized(message: message, signatures: signatures) + if !isSigValid { + log("Error unlocking Flow tokens, signatures are incorrect") + emit NoticeError(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex, error: "Signatures are incorrect") + return false + } + + // Check invocation status of the notice + let noticeHash = self.buildNoticeHash(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex) + if self.invokedNotices.contains(noticeHash) { + log("Notice replay") + emit NoticeError(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex, error: "Notice replay") + return false + } + // Mark notice as being invoked + self.invokedNotices.append(noticeHash) + + // Check that notice has a correct era + let startNextEra: Bool = noticeEraId == self.eraId + UInt256(1) && noticeEraIndex == UInt256(0) + if !(noticeEraId <= self.eraId || startNextEra) { + log("Notice must use existing era or start next era") + emit NoticeError(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex, error: "Notice must use existing era or start next era") + return false + } + // Update era + if startNextEra { + self.eraId = self.eraId + UInt256(1); + } + + return true + } + + pub fun changeAuthorities(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + newAuthorities: [String], + signatures: [String]) { + pre { + newAuthorities.length > 0: "New authority set can not be empty" + } + + // Build `changeAuthorities` notice message + let message = self.buildChangeAuthoritiesMessage( + noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + parentNoticeHex: parentNoticeHex, + newAuthorities: newAuthorities) + + // Validate notice's signatures, invocation status and era ids + if !self.isValidNotice(noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + message: message, + signatures: signatures) { + log("Invalid Notice") + return + } + + Starport.authorities = newAuthorities + + emit ChangeAuthorities(newAuthorities: newAuthorities) + } + + pub fun buildChangeAuthoritiesMessage(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + newAuthorities: [String]): [UInt8] { + var message = self.changeAuthoritiesHex.decodeHex() + .concat(noticeEraId.toBigEndianBytes()) + .concat(noticeEraIndex.toBigEndianBytes()) + .concat(parentNoticeHex.decodeHex()) + + for newAuthority in newAuthorities { + message = message.concat(newAuthority.decodeHex()) + } + + return message + } + + pub fun setSupplyCap(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + supplyCap: UFix64, + signatures: [String]) { + // Build `setSupplyCap` notice message + let message = self.buildSetSupplyCapMessage( + noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + parentNoticeHex: parentNoticeHex, + supplyCap: supplyCap) + + // Validate notice's signatures, invocation status and era ids + if !self.isValidNotice(noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + message: message, + signatures: signatures) { + log("Invalid Notice") + return + } + + emit NewSupplyCap(asset: "FLOW", supplyCap: supplyCap); + + Starport.supplyCaps["FLOW"] = supplyCap; + } + + pub fun buildSetSupplyCapMessage(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + supplyCap: UFix64): [UInt8] { + let message = self.setSupplyCapHex.decodeHex() + .concat(noticeEraId.toBigEndianBytes()) + .concat(noticeEraIndex.toBigEndianBytes()) + .concat(parentNoticeHex.decodeHex()) + .concat(self.flowAssetHex.decodeHex()) + .concat(supplyCap.toBigEndianBytes()) + return message + } + + init() { + // Create a new Starport Vault and save it in storage + self.vault <- FlowToken.createEmptyVault() as! @FlowToken.Vault + + // Create a new Admin resource + let admin <- create Administrator() + self.account.save(<-admin, to: /storage/admin) + + // Set intitial values + self.authorities = [] + self.eraId = UInt256(0) + self.invokedNotices = [] + self.supplyCaps = {} + // `unlock` method name hex encoded + self.unlockHex = "756e6c6f636b" + // `changeAuthorities` method name hex encoded + self.changeAuthoritiesHex = "6368616e6765417574686f726974696573" + self.setSupplyCapHex = "736574537570706c79436170" + // `FLOW` asset name in hex + self.flowAssetHex = "464c4f57" + } +} \ No newline at end of file diff --git a/flow/cadence/scripts/build_change_authorities_message.cdc b/flow/cadence/scripts/build_change_authorities_message.cdc new file mode 100644 index 000000000..64212bc63 --- /dev/null +++ b/flow/cadence/scripts/build_change_authorities_message.cdc @@ -0,0 +1,10 @@ +// This script returns the message to change authorities of Starport + +import Starport from 0xc8873a26b148ed14 + +pub fun main(noticeEraId: UInt256, noticeEraIndex: UInt256, parentNoticeHex: String, newAuthorities: [String]): [UInt8] { + + let message = Starport.buildChangeAuthoritiesMessage(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex, parentNoticeHex: parentNoticeHex, newAuthorities: newAuthorities) + + return message +} \ No newline at end of file diff --git a/flow/cadence/scripts/build_set_supply_cap_message.cdc b/flow/cadence/scripts/build_set_supply_cap_message.cdc new file mode 100644 index 000000000..0c19068ab --- /dev/null +++ b/flow/cadence/scripts/build_set_supply_cap_message.cdc @@ -0,0 +1,10 @@ +// This script returns the message to change authorities of Starport + +import Starport from 0xc8873a26b148ed14 + +pub fun main(noticeEraId: UInt256, noticeEraIndex: UInt256, parentNoticeHex: String, supplyCap: UFix64): [UInt8] { + + let message = Starport.buildSetSupplyCapMessage(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex, parentNoticeHex: parentNoticeHex, supplyCap: supplyCap) + + return message +} \ No newline at end of file diff --git a/flow/cadence/scripts/build_unlock_message.cdc b/flow/cadence/scripts/build_unlock_message.cdc new file mode 100644 index 000000000..4c18d3119 --- /dev/null +++ b/flow/cadence/scripts/build_unlock_message.cdc @@ -0,0 +1,10 @@ +// This script returns the message to change authorities of Starport + +import Starport from 0xc8873a26b148ed14 + +pub fun main(noticeEraId: UInt256, noticeEraIndex: UInt256, parentNoticeHex: String, toAddress: Address, amount: UFix64): [UInt8] { + + let message = Starport.buildUnlockMessage(noticeEraId: noticeEraId, noticeEraIndex: noticeEraIndex, parentNoticeHex: parentNoticeHex, toAddress: toAddress, amount: amount) + + return message +} \ No newline at end of file diff --git a/flow/cadence/scripts/get_account_flow_balance.cdc b/flow/cadence/scripts/get_account_flow_balance.cdc new file mode 100644 index 000000000..3226aa546 --- /dev/null +++ b/flow/cadence/scripts/get_account_flow_balance.cdc @@ -0,0 +1,17 @@ +// This script reads the balance field of an account's FlowToken Balance + +// import FlowToken from 0x0ae53cb6e3f42a79 +// import FungibleToken from 0xee82856bf20e2aa6 + +import FungibleToken from 0x9a0766d93b6608b7 +import FlowToken from 0x7e60df042a9c0868 + +pub fun main(account: Address): UFix64 { + + let vaultRef = getAccount(account) + .getCapability(/public/flowTokenBalance) + .borrow<&FlowToken.Vault{FungibleToken.Balance}>() + ?? panic("Could not borrow Balance reference to the Vault") + + return vaultRef.balance +} \ No newline at end of file diff --git a/flow/cadence/scripts/get_authorities.cdc b/flow/cadence/scripts/get_authorities.cdc new file mode 100644 index 000000000..619aaf36a --- /dev/null +++ b/flow/cadence/scripts/get_authorities.cdc @@ -0,0 +1,10 @@ +// This script reads a set of Starport authoritites + +import Starport from 0xc8873a26b148ed14 + +pub fun main(): [String] { + + let authorities = Starport.getAuthorities() + + return authorities +} \ No newline at end of file diff --git a/flow/cadence/scripts/get_era_id.cdc b/flow/cadence/scripts/get_era_id.cdc new file mode 100644 index 000000000..4766196d1 --- /dev/null +++ b/flow/cadence/scripts/get_era_id.cdc @@ -0,0 +1,10 @@ +// This script reads an era id + +import Starport from 0xc8873a26b148ed14 + +pub fun main(): UInt256 { + + let eraId = Starport.getEraId() + + return eraId +} \ No newline at end of file diff --git a/flow/cadence/scripts/get_flow_supply_cap.cdc b/flow/cadence/scripts/get_flow_supply_cap.cdc new file mode 100644 index 000000000..63d0ea21e --- /dev/null +++ b/flow/cadence/scripts/get_flow_supply_cap.cdc @@ -0,0 +1,10 @@ +// This script reads the amount of locked Flow tokens + +import Starport from 0xc8873a26b148ed14 + +pub fun main(): UFix64 { + + let supplyCap = Starport.getFlowSupplyCap() + + return supplyCap +} \ No newline at end of file diff --git a/flow/cadence/scripts/get_locked_balance.cdc b/flow/cadence/scripts/get_locked_balance.cdc new file mode 100644 index 000000000..fdf904a7f --- /dev/null +++ b/flow/cadence/scripts/get_locked_balance.cdc @@ -0,0 +1,10 @@ +// This script reads the amount of locked Flow tokens + +import Starport from 0xc8873a26b148ed14 + +pub fun main(): UFix64 { + + let amount = Starport.getLockedBalance() + + return amount +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/change_authorities_admin.cdc b/flow/cadence/transactions/starport/change_authorities_admin.cdc new file mode 100644 index 000000000..64ccd30d5 --- /dev/null +++ b/flow/cadence/transactions/starport/change_authorities_admin.cdc @@ -0,0 +1,17 @@ +// Update new authorities addresses +import Starport from 0xc8873a26b148ed14 + +transaction(authorities: [String]) { + let admin: &Starport.Administrator + + prepare(signer: AuthAccount) { + + self.admin = signer.borrow<&Starport.Administrator>(from: /storage/admin) + ?? panic("Could not borrow reference to storage Starport Participant") + } + + execute { + + self.admin.changeAuthorities(newAuthorities: authorities) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/change_authorities_notice.cdc b/flow/cadence/transactions/starport/change_authorities_notice.cdc new file mode 100644 index 000000000..8b9bd1b88 --- /dev/null +++ b/flow/cadence/transactions/starport/change_authorities_notice.cdc @@ -0,0 +1,24 @@ +// Unlock Flow tokens with given authorities signatures +import Starport from 0xc8873a26b148ed14 + +transaction(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + newAuthorities: [String], + signatures: [String]) { + + prepare(signer: AuthAccount) { + + } + + execute { + + Starport.changeAuthorities( + noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + parentNoticeHex: parentNoticeHex, + newAuthorities: newAuthorities, + signatures: signatures, + ) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/lock_flow_tokens.cdc b/flow/cadence/transactions/starport/lock_flow_tokens.cdc new file mode 100644 index 000000000..ae190a26d --- /dev/null +++ b/flow/cadence/transactions/starport/lock_flow_tokens.cdc @@ -0,0 +1,34 @@ +// Lock Flow Tokens +// import FlowToken from 0x0ae53cb6e3f42a79 +// import FungibleToken from 0xee82856bf20e2aa6 +import FungibleToken from 0x9a0766d93b6608b7 +import FlowToken from 0x7e60df042a9c0868 +import Starport from 0xc8873a26b148ed14 + +transaction(lockAmount: UFix64) { + // let tokenAdmin: &FlowToken.Administrator + let participant: &{Starport.FlowLock} + + // The Vault resource that holds the tokens that are being transferred + let sentVault: @FungibleToken.Vault + + prepare(signer: AuthAccount) { + // Get a reference to the signer's stored vault + let vaultRef = signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) + ?? panic("Could not borrow reference to the owner's Vault!") + + // Withdraw tokens from the signer's stored vault + self.sentVault <- vaultRef.withdraw(amount: lockAmount) + + // Get an access to Starport Participant for locking Flow tokens + self.participant = signer + .getCapability(/public/participant) + .borrow<&{Starport.FlowLock}>() + ?? panic("Could not borrow Starport participant") + } + + execute { + // Lock tokens in Starport + self.participant.lock(from: <-self.sentVault) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/set_supply_cap_admin.cdc b/flow/cadence/transactions/starport/set_supply_cap_admin.cdc new file mode 100644 index 000000000..49215dba5 --- /dev/null +++ b/flow/cadence/transactions/starport/set_supply_cap_admin.cdc @@ -0,0 +1,17 @@ +// Update new authorities addresses +import Starport from 0xc8873a26b148ed14 + +transaction(supplyCap: UFix64) { + let admin: &Starport.Administrator + + prepare(signer: AuthAccount) { + + self.admin = signer.borrow<&Starport.Administrator>(from: /storage/admin) + ?? panic("Could not borrow reference to storage Starport Participant") + } + + execute { + + self.admin.setSupplyCap(supplyCap: supplyCap) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/set_supply_cap_notice.cdc b/flow/cadence/transactions/starport/set_supply_cap_notice.cdc new file mode 100644 index 000000000..43c667907 --- /dev/null +++ b/flow/cadence/transactions/starport/set_supply_cap_notice.cdc @@ -0,0 +1,24 @@ +// Unlock Flow tokens with given authorities signatures +import Starport from 0xc8873a26b148ed14 + +transaction(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + supplyCap: UFix64, + signatures: [String]) { + + prepare(signer: AuthAccount) { + + } + + execute { + + Starport.setSupplyCap( + noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + parentNoticeHex: parentNoticeHex, + supplyCap: supplyCap, + signatures: signatures, + ) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/setup_starport_user.cdc b/flow/cadence/transactions/starport/setup_starport_user.cdc new file mode 100644 index 000000000..60167ee34 --- /dev/null +++ b/flow/cadence/transactions/starport/setup_starport_user.cdc @@ -0,0 +1,28 @@ +// Lock Flow Tokens +// import FlowToken from 0x0ae53cb6e3f42a79 +import FlowToken from 0x7e60df042a9c0868 +import Starport from 0xc8873a26b148ed14 + +transaction() { + + let participant: Address + + prepare(signer: AuthAccount) { + + self.participant = signer.address + + let starport <- Starport.createStarportParticipant(); + // Store the vault in the account storage + signer.save<@Starport.StarportParticipant>(<-starport, to: /storage/starportParticipant) + + signer.link<&Starport.StarportParticipant{Starport.FlowLock}>(/public/participant, target: /storage/starportParticipant) + + log("Starport participant was stored") + } + + execute { + getAccount(self.participant) + .getCapability(/public/participant).borrow<&Starport.StarportParticipant{Starport.FlowLock}>() + ?? panic("Could not borrow Starport participant") + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/unlock_flow_tokens_admin.cdc b/flow/cadence/transactions/starport/unlock_flow_tokens_admin.cdc new file mode 100644 index 000000000..538ca8423 --- /dev/null +++ b/flow/cadence/transactions/starport/unlock_flow_tokens_admin.cdc @@ -0,0 +1,15 @@ +// Update new authorities addresses +import Starport from 0xc8873a26b148ed14 + +transaction(toAddress: Address, amount: UFix64) { + let admin: &Starport.Administrator + + prepare(signer: AuthAccount) { + self.admin = signer.borrow<&Starport.Administrator>(from: /storage/admin) + ?? panic("Could not borrow reference to storage Starport Participant") + } + + execute { + self.admin.unlock(toAddress: toAddress, amount: amount) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/unlock_flow_tokens_notice.cdc b/flow/cadence/transactions/starport/unlock_flow_tokens_notice.cdc new file mode 100644 index 000000000..5e24ae50e --- /dev/null +++ b/flow/cadence/transactions/starport/unlock_flow_tokens_notice.cdc @@ -0,0 +1,25 @@ +// Unlock Flow tokens with given authorities signatures +import Starport from 0xc8873a26b148ed14 + +transaction(noticeEraId: UInt256, + noticeEraIndex: UInt256, + parentNoticeHex: String, + signatures: [String], + toAddress: Address, + amount: UFix64) { + + prepare(signer: AuthAccount) { + } + + execute { + + Starport.unlock( + noticeEraId: noticeEraId, + noticeEraIndex: noticeEraIndex, + parentNoticeHex: parentNoticeHex, + toAddress: toAddress, + amount: amount, + signatures: signatures, + ) + } +} \ No newline at end of file diff --git a/flow/cadence/transactions/starport/withdraw_flow_tokens.cdc b/flow/cadence/transactions/starport/withdraw_flow_tokens.cdc new file mode 100644 index 000000000..9a22e9d9f --- /dev/null +++ b/flow/cadence/transactions/starport/withdraw_flow_tokens.cdc @@ -0,0 +1,21 @@ +// Withdraw Locked Flow Tokens +//import FlowToken from 0x0ae53cb6e3f42a79 +import FlowToken from 0x7e60df042a9c0868 +import Starport from 0xc8873a26b148ed14 + +transaction(lockedAmount: UFix64) { + let admin: &Starport.Administrator + + prepare(signer: AuthAccount) { + + self.admin = signer.borrow<&Starport.Administrator>(from: /storage/admin) + ?? panic("Could not borrow reference to storage Starport Participant") + } + + execute { + + let vault <- self.admin.withdrawLockedFlowTokens(amount: lockedAmount) + destroy vault + + } +} \ No newline at end of file diff --git a/flow/fcl/get_locked_balance.js b/flow/fcl/get_locked_balance.js new file mode 100644 index 000000000..dbf4faaf0 --- /dev/null +++ b/flow/fcl/get_locked_balance.js @@ -0,0 +1,13 @@ +import * as fcl from "@onflow/fcl" +import * as t from "@onflow/types" + +await fcl.send([ + fcl.script` + import Starport from 0xc8873a26b148ed14 + + pub fun main(): UFix64 { + let amount = Starport.getLockedBalance() + return amount + } + ` + ]).then(fcl.decode) \ No newline at end of file diff --git a/flow/fcl/lock_flow_tokens.js b/flow/fcl/lock_flow_tokens.js new file mode 100644 index 000000000..15736ff27 --- /dev/null +++ b/flow/fcl/lock_flow_tokens.js @@ -0,0 +1,49 @@ +import * as fcl from "@onflow/fcl" +import * as t from "@onflow/types" + +const txId = await fcl + .send([ + // Transactions use fcl.transaction instead of fcl.script + // Their syntax is a little different too + fcl.transaction` + import FungibleToken from 0x9a0766d93b6608b7 + import FlowToken from 0x7e60df042a9c0868 + import Starport from 0xc8873a26b148ed14 + + transaction(lockAmount: UFix64) { + // let tokenAdmin: &FlowToken.Administrator + let participant: &{Starport.FlowLock} + + // The Vault resource that holds the tokens that are being transferred + let sentVault: @FungibleToken.Vault + + prepare(signer: AuthAccount) { + // Get a reference to the signer's stored vault + let vaultRef = signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) + ?? panic("Could not borrow reference to the owner's Vault!") + + // Withdraw tokens from the signer's stored vault + self.sentVault <- vaultRef.withdraw(amount: lockAmount) + + // Get an access to Starport Participant for locking Flow tokens + self.participant = signer + .getCapability(/public/participant) + .borrow<&{Starport.FlowLock}>() + ?? panic("Could not borrow Starport participant") + } + + execute { + // Lock tokens in Starport + self.participant.lock(from: <-self.sentVault) + } + } + `, + fcl.payer(fcl.authz), // current user is responsible for paying for the transaction + fcl.proposer(fcl.authz), // current user acting as the nonce + fcl.authorizations([fcl.authz]), // current user will be first AuthAccount + fcl.limit(70), // set the compute limit + fcl.args([ + fcl.arg("100.0", t.UFix64), // name + ]) + ]) + .then(fcl.decode) \ No newline at end of file diff --git a/flow/fcl/setup_starport_user.js b/flow/fcl/setup_starport_user.js new file mode 100644 index 000000000..fb181453a --- /dev/null +++ b/flow/fcl/setup_starport_user.js @@ -0,0 +1,33 @@ +import * as fcl from "@onflow/fcl" +import * as t from "@onflow/types" + +const txId = await fcl + .send([ + // Transactions use fcl.transaction instead of fcl.script + // Their syntax is a little different too + fcl.transaction` + import FlowToken from 0x7e60df042a9c0868 + import Starport from 0xc8873a26b148ed14 + transaction() { + let participant: Address + prepare(signer: AuthAccount) { + self.participant = signer.address + let starport <- Starport.createStarportParticipant(); + // Store the vault in the account storage + signer.save<@Starport.StarportParticipant>(<-starport, to: /storage/starportParticipant) + signer.link<&Starport.StarportParticipant{Starport.FlowLock}>(/public/participant, target: /storage/starportParticipant) + log("Starport participant was stored") + } + execute { + getAccount(self.participant) + .getCapability(/public/participant).borrow<&Starport.StarportParticipant{Starport.FlowLock}>() + ?? panic("Could not borrow Starport participant") + } + } + `, + fcl.payer(fcl.authz), // current user is responsible for paying for the transaction + fcl.proposer(fcl.authz), // current user acting as the nonce + fcl.authorizations([fcl.authz]), // current user will be first AuthAccount + fcl.limit(70), // set the compute limit + ]) + .then(fcl.decode) \ No newline at end of file diff --git a/flow/flow-fetcher/.gitignore b/flow/flow-fetcher/.gitignore new file mode 100644 index 000000000..723ef36f4 --- /dev/null +++ b/flow/flow-fetcher/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file diff --git a/flow/flow-fetcher/README.md b/flow/flow-fetcher/README.md new file mode 100644 index 000000000..3921df297 --- /dev/null +++ b/flow/flow-fetcher/README.md @@ -0,0 +1,7 @@ +Go server for fetching Starport events from Flow + +to run: +`go run *.go` + +to fetch `Lock` events: +`curl -X GET http://localhost:8089/events -H "Content-type: application/json" -d '{"topic": "A.c8873a26b148ed14.Starport.Lock", "StartHeight": 34944396, "EndHeight": 34944396}'` \ No newline at end of file diff --git a/flow/flow-fetcher/blocks.go b/flow/flow-fetcher/blocks.go new file mode 100644 index 000000000..58ab7a23b --- /dev/null +++ b/flow/flow-fetcher/blocks.go @@ -0,0 +1,67 @@ +// File: blocks.go +package main + +import ( + "context" + "fmt" + + "github.com/onflow/flow-go-sdk" + "github.com/onflow/flow-go-sdk/client" +) + +type Block struct { + BlockId string `json:"blockId"` + ParentBlockId string `json:"parentBlockId"` + Height uint64 `json:"height"` + Timestamp string `json:"timestamp"` +} + +func getLatestBlock(flowClient *client.Client) (Block, error) { + // Fetching only sealed blocks here + isSealed := true + latestBlock, err := flowClient.GetLatestBlock(context.Background(), isSealed) + if err != nil { + return Block{}, err + } + + fmt.Println("Latest block: ", latestBlock) + + var blockRes = Block{ + BlockId: latestBlock.ID.String(), + ParentBlockId: latestBlock.ParentID.String(), + Height: latestBlock.Height, + Timestamp: latestBlock.Timestamp.String(), + } + + return blockRes, nil +} + +func getBlock(flowClient *client.Client, blockInfo FlowBlockInfo) (Block, error) { + // If height and id of block are no set, return the latest block + if blockInfo.Id == "" && blockInfo.Height == 0 { + return getLatestBlock(flowClient) + } + + block, err := func() (*flow.Block, error) { + if blockInfo.Height == 0 { + return flowClient.GetBlockByID(context.Background(), flow.HexToID(blockInfo.Id)) + } else { + return flowClient.GetBlockByHeight(context.Background(), blockInfo.Height) + } + }() + + if err != nil { + return Block{}, err + } + + fmt.Printf("Block %+v for data %+v:\n", block, blockInfo) + + blockRes := Block{ + BlockId: block.ID.String(), + ParentBlockId: block.ParentID.String(), + Height: block.Height, + Timestamp: block.Timestamp.String(), + } + + return blockRes, nil +} diff --git a/flow/flow-fetcher/events.go b/flow/flow-fetcher/events.go new file mode 100644 index 000000000..3761c3be0 --- /dev/null +++ b/flow/flow-fetcher/events.go @@ -0,0 +1,70 @@ +// File: events.go +package main + +import ( + "context" + "fmt" + + "github.com/onflow/flow-go-sdk/client" + "github.com/toni/flow-fetcher/starport" +) + +type FlowEvent struct { + BlockId string `json:"blockId"` + BlockHeight uint64 `json:"blockHeight"` + TransactionId string `json:"transactionId"` + TransactionIndex int `json:"transactionIndex"` + EventIndex int `json:"eventIndex"` + Topic string `json:"topic"` + Data string `json:"data"` +} + +// type LockData struct { +// Asset string `json:"asset"` +// Recipient string `json:"recipient"` +// Amount float64 `json:"amount"` +// } + +func getLockEvents(flowClient *client.Client, eventsInfo FlowEventsInfo) ([]FlowEvent, error) { + // fetch block events of Starport for the specified range of blocks + var events []FlowEvent + blockEvents, err := flowClient.GetEventsForHeightRange(context.Background(), client.EventRangeQuery{ + Type: eventsInfo.Topic, + StartHeight: eventsInfo.StartHeight, + EndHeight: eventsInfo.EndHeight, + }) + if err != nil { + return events, err + } + fmt.Println("Block events: ", blockEvents) + + for _, blockEvent := range blockEvents { + for _, lockEvent := range blockEvent.Events { + // loop through the Starport.Lock events in this blockEvent + event := starport.FlowLockEvent(lockEvent.Value) + fmt.Println("Lock event = ", event) + fmt.Printf("transactionID: %s, block height: %d\n", + lockEvent.TransactionID.String(), blockEvent.Height) + + // Build Lock event result data + var eventRes = FlowEvent{ + BlockId: blockEvent.BlockID.String(), + BlockHeight: blockEvent.Height, + TransactionId: lockEvent.TransactionID.String(), + TransactionIndex: lockEvent.TransactionIndex, + EventIndex: lockEvent.EventIndex, + Topic: lockEvent.Type, + Data: fmt.Sprintf("{\"asset\":\"%s\",\"recipient\":\"%s\",\"amount\":%d}", event.Asset(), event.Recipient(), event.Amount()), + } + + // // Lock specific fields + // Asset: event.Asset(), + // Recipient: event.Recipient().String(), + // Amount: event.Amount(), + // } + events = append(events, eventRes) + } + } + + return events, nil +} diff --git a/flow/flow-fetcher/go.mod b/flow/flow-fetcher/go.mod new file mode 100644 index 000000000..3dca5d6fe --- /dev/null +++ b/flow/flow-fetcher/go.mod @@ -0,0 +1,10 @@ +module github.com/toni/flow-fetcher + +go 1.15 + +require ( + github.com/golang/gddo v0.0.0-20210115222349-20d68f94ee1f + github.com/onflow/cadence v0.9.0 + github.com/onflow/flow-go-sdk v0.10.0 + google.golang.org/grpc v1.32.0 +) diff --git a/flow/flow-fetcher/go.sum b/flow/flow-fetcher/go.sum new file mode 100644 index 000000000..2a63ca6bd --- /dev/null +++ b/flow/flow-fetcher/go.sum @@ -0,0 +1,292 @@ +cloud.google.com/go v0.16.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/Azure/azure-pipeline-go v0.2.1/go.mod h1:UGSo8XybXnIGZ3epmeBw7Jdz+HiUVpqIlpz/HKHylF4= +github.com/Azure/azure-pipeline-go v0.2.2/go.mod h1:4rQ/NZncSvGqNkkOsNpOU1tgoNuIlp9AfUH5G1tvCHc= +github.com/Azure/azure-storage-blob-go v0.7.0/go.mod h1:f9YQKtsG1nMisotuTPpO0tjNuEjKRYAcJU8/ydDI++4= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/adal v0.8.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/OneOfOne/xxhash v1.2.5/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q= +github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= +github.com/VictoriaMetrics/fastcache v1.5.3/go.mod h1:+jv9Ckb+za/P1ZRg/sulP5Ni1v49daAVERr0H3CuscE= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= +github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847/go.mod h1:D/tb0zPVXnP7fmsLZjtdUhSsumbK/ij54UXjjVgMGxQ= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/bradfitz/gomemcache v0.0.0-20170208213004-1952afaa557d/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6 h1:Eey/GGQ/E5Xp1P2Lyx1qj007hLZfbi0+CoVeJruGCtI= +github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6/go.mod h1:Dmm/EzmjnCiweXmzRIAiUWCInVmPgjkzgv5k4tVyXiQ= +github.com/c-bata/go-prompt v0.2.3/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.0.1-0.20190104013014-3767db7a7e18/go.mod h1:HD5P3vAIAh+Y2GAxg0PrPN1P8WkepXGpjbUPDHJqqKM= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/cloudflare-go v0.10.2-0.20190916151808-a80f83b9add9/go.mod h1:1MxXX1Ux4x6mqPmjkUgTP1CdXIBXKX7T+Jk9Gxrmx+U= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/edsrzf/mmap-go v0.0.0-20160512033002-935e0e8a636c/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/gosigar v0.8.1-0.20180330100440-37f05ff46ffa/go.mod h1:cdorVVzy1fhmEqmtgqkoE3bYtCfSCkVyjTyCIo22xvs= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/ethereum/go-ethereum v1.9.9 h1:jnoBvjH8aMH++iH14XmiJdAsnRcmZUM+B5fsnEZBVE0= +github.com/ethereum/go-ethereum v1.9.9/go.mod h1:a9TqabFudpDu1nucId+k9S8R9whYaHnGBLKFouA5EAo= +github.com/fatih/color v1.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= +github.com/fsnotify/fsnotify v1.4.3-0.20170329110642-4da3e2cfbabc/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fxamacker/cbor/v2 v2.2.0 h1:6eXqdDDe588rSYAi1HfZKbx6YYQO4mxQ9eC6xYpU/JQ= +github.com/fxamacker/cbor/v2 v2.2.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo= +github.com/garyburd/redigo v1.1.1-0.20170914051019-70e1b1943d4f/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= +github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= +github.com/go-stack/stack v1.6.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-test/deep v1.0.5 h1:AKODKU3pDH1RzZzm6YZu77YWtEAq6uh1rLIAQlay2qc= +github.com/go-test/deep v1.0.5/go.mod h1:QV8Hv/iy04NyLBxAdO9njL0iVPN1S4d/A3NVv1V36o8= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/gddo v0.0.0-20210115222349-20d68f94ee1f h1:16RtHeWGkJMc80Etb8RPCcKevXGldr57+LOyZt8zOlg= +github.com/golang/gddo v0.0.0-20210115222349-20d68f94ee1f/go.mod h1:ijRvpgDJDI262hYq/IQVYgf8hd8IHUs93Ol0kvMBAx4= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/lint v0.0.0-20170918230701-e5d664eb928e/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2-0.20190517061210-b285ee9cfc6c/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5 h1:F768QJ1E9tib+q5Sc8MkdJi1RxLTbRcTf8LJV56aRls= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.1.1-0.20171103154506-982329095285/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= +github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/graph-gophers/graphql-go v0.0.0-20191115155744-f33e81362277/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= +github.com/gregjones/httpcache v0.0.0-20170920190843-316c5e0ff04e/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/hashicorp/golang-lru v0.0.0-20160813221303-0a025b7e63ad/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hcl v0.0.0-20170914154624-68e816d1c783/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huin/goupnp v0.0.0-20161224104101-679507af18f3/go.mod h1:MZ2ZmwcBpvOoJ22IJsc7va19ZwoheaBk43rKg12SKag= +github.com/inconshreveable/log15 v0.0.0-20170622235902-74a0988b5f80/go.mod h1:cOaXtrgN4ScfRrD9Bre7U1thNq5RtJ8ZoP4iXVGRj6o= +github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= +github.com/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= +github.com/julienschmidt/httprouter v1.1.1-0.20170430222011-975b5c4c7c21/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= +github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/logrusorgru/aurora v0.0.0-20200102142835-e9ef32dff381 h1:bqDmpDG49ZRnB5PcgP0RXtQvnMSgIF14M7CBd2shtXs= +github.com/logrusorgru/aurora v0.0.0-20200102142835-e9ef32dff381/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= +github.com/magiconair/properties v1.7.4-0.20170902060319-8d7837e64d3c/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.0.10-0.20170816031813-ad5389df28cd/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-ieproxy v0.0.0-20190610004146-91bb50d98149/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= +github.com/mattn/go-ieproxy v0.0.0-20190702010315-6dee0af9227d/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= +github.com/mattn/go-isatty v0.0.2/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.5-0.20180830101745-3fb116b82035/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v0.0.0-20170523030023-d0303fe80992/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0= +github.com/naoina/toml v0.1.2-0.20170918210437-9fafd6967416/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/olekukonko/tablewriter v0.0.2-0.20190409134802-7e037d187b0c/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onflow/cadence v0.8.0/go.mod h1:R43uGnqQsTcnFf1fMPCcMjDPplBIzbR5XkFZRF2OH3Y= +github.com/onflow/cadence v0.9.0 h1:PWfpVVDdVhfq0FxCobTbFM0WN/ebexD6nr67YkVdNRc= +github.com/onflow/cadence v0.9.0/go.mod h1:R43uGnqQsTcnFf1fMPCcMjDPplBIzbR5XkFZRF2OH3Y= +github.com/onflow/flow-go-sdk v0.10.0 h1:WGfpb6i7nwCpeptTEtdEPCvcfookQn0Vzu2egCeqoEk= +github.com/onflow/flow-go-sdk v0.10.0/go.mod h1:nSEpZxI2oWx1H6nAxz/ro1uVrqtDUn62heVFoaXHV2E= +github.com/onflow/flow/protobuf/go/flow v0.1.5 h1:OQJhjreSkzV8nsBpx6yJNtCaGdqe5xYn83IkcFMERGU= +github.com/onflow/flow/protobuf/go/flow v0.1.5/go.mod h1:kRugbzZjwQqvevJhrnnCFMJZNmoSJmxlKt6hTGXZojM= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/pborman/uuid v0.0.0-20170112150404-1b00554d8222/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34= +github.com/pelletier/go-toml v1.0.1-0.20170904195809-1d6b12b7cb29/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/tsdb v0.6.2-0.20190402121629-4f204dcbc150/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/raviqqe/hamt v0.0.0-20190615202029-864fb7caef85 h1:FG/cFwuZM0j3eEBI5jkkYRn6RufVzcvtTXN+YFHWJjI= +github.com/raviqqe/hamt v0.0.0-20190615202029-864fb7caef85/go.mod h1:I9elsTaXMhu41qARmzefHy7v2KmAV2TB1yH4E+nBSf0= +github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= +github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= +github.com/robertkrimen/otto v0.0.0-20170205013659-6a77b7cbc37d/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY= +github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/rs/xhandler v0.0.0-20160618193221-ed27b6fd6521/go.mod h1:RvLn4FgxWubrpZHtQLnOf6EwhN2hEMusxZOhcW9H3UQ= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/segmentio/fasthash v1.0.2 h1:86fGDl2hB+iSHYlccB/FP9qRGvLNuH/fhEEFn6gnQUs= +github.com/segmentio/fasthash v1.0.2/go.mod h1:waKX8l2N8yckOgmSsXJi7x1ZfdKZ4x7KRMzBtS3oedY= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spaolacci/murmur3 v1.0.1-0.20190317074736-539464a789e9/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v0.0.0-20170901052352-ee1bd8ee15a1/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cast v1.1.0/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg= +github.com/spf13/jwalterweatherman v0.0.0-20170901151539-12bd96e66386/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.1-0.20170901120850-7aff26db30c1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/viper v1.0.0/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM= +github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4/go.mod h1:RZLeN1LMWmRsyYjvAu+I6Dm9QmlDaIIt+Y+4Kd7Tp+Q= +github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw= +github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= +github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= +github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208/go.mod h1:IotVbo4F+mw0EzQ08zFqg7pK3FebNXpaMsRy2RT+Ees= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.uber.org/goleak v1.0.0 h1:qsup4IcBdlmsnGfqyLl4Ntn3C2XCCuKAE7DwHpScyUo= +go.uber.org/goleak v1.0.0/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200423211502-4bdfaf469ed5 h1:Q7tZBpemrlsc2I7IyODzhtallWRSm4Q0d09pL6XbQtU= +golang.org/x/crypto v0.0.0-20200423211502-4bdfaf469ed5/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/oauth2 v0.0.0-20170912212905-13449ad91cb2/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20170517211232-f52d1811a629/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20170424234030-8be79e1e0910/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200323144430-8dcfad9e016e h1:ssd5ulOvVWlh4kDSUF2SqzmMeWfjmwDXM+uGw/aQjRE= +golang.org/x/tools v0.0.0-20200323144430-8dcfad9e016e/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.0.0-20170921000349-586095a6e407/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20170918111702-1e559d0a00ee/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.2.1-0.20170921194603-d4b75ebd4f9f/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.32.0 h1:zWTV+LMdc3kaiJMSTOFz2UgSBgx8RNQoTGiZu3fR9S0= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= +gopkg.in/olebedev/go-duktape.v3 v3.0.0-20190213234257-ec84240a7772/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= +gopkg.in/sourcemap.v1 v1.0.5/go.mod h1:2RlvNNSMglmRrcvhfuzp4hQHwOtjxlbjX7UPY/GXb78= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5 h1:ymVxjfMaHvXD8RqPRmzHHsB3VvucivSkIAvJFDI5O3c= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/flow/flow-fetcher/helpers.go b/flow/flow-fetcher/helpers.go new file mode 100644 index 000000000..75cff1932 --- /dev/null +++ b/flow/flow-fetcher/helpers.go @@ -0,0 +1,81 @@ +// File: helpers.go +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "github.com/golang/gddo/httputil/header" +) + +type malformedRequest struct { + status int + msg string +} + +func (mr *malformedRequest) Error() string { + return mr.msg +} + +func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error { + if r.Header.Get("Content-Type") != "" { + value, _ := header.ParseValueAndParams(r.Header, "Content-Type") + if value != "application/json" { + msg := "Content-Type header is not application/json" + return &malformedRequest{status: http.StatusUnsupportedMediaType, msg: msg} + } + } + + r.Body = http.MaxBytesReader(w, r.Body, 1048576) + + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + + err := dec.Decode(&dst) + if err != nil { + var syntaxError *json.SyntaxError + var unmarshalTypeError *json.UnmarshalTypeError + + switch { + case errors.As(err, &syntaxError): + msg := fmt.Sprintf("Request body contains badly-formed JSON (at position %d)", syntaxError.Offset) + return &malformedRequest{status: http.StatusBadRequest, msg: msg} + + case errors.Is(err, io.ErrUnexpectedEOF): + msg := fmt.Sprintf("Request body contains badly-formed JSON") + return &malformedRequest{status: http.StatusBadRequest, msg: msg} + + case errors.As(err, &unmarshalTypeError): + msg := fmt.Sprintf("Request body contains an invalid value for the %q field (at position %d)", unmarshalTypeError.Field, unmarshalTypeError.Offset) + return &malformedRequest{status: http.StatusBadRequest, msg: msg} + + case strings.HasPrefix(err.Error(), "json: unknown field "): + fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ") + msg := fmt.Sprintf("Request body contains unknown field %s", fieldName) + return &malformedRequest{status: http.StatusBadRequest, msg: msg} + + case errors.Is(err, io.EOF): + msg := "Request body must not be empty" + return &malformedRequest{status: http.StatusBadRequest, msg: msg} + + case err.Error() == "http: request body too large": + msg := "Request body must not be larger than 1MB" + return &malformedRequest{status: http.StatusRequestEntityTooLarge, msg: msg} + + default: + return err + } + } + + err = dec.Decode(&struct{}{}) + if err != io.EOF { + msg := "Request body must only contain a single JSON object" + return &malformedRequest{status: http.StatusBadRequest, msg: msg} + } + + return nil +} \ No newline at end of file diff --git a/flow/flow-fetcher/main.go b/flow/flow-fetcher/main.go new file mode 100644 index 000000000..1844a683f --- /dev/null +++ b/flow/flow-fetcher/main.go @@ -0,0 +1,198 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "net/http" + "os" + + "google.golang.org/grpc" + + "github.com/onflow/flow-go-sdk/client" +) + +type FlowEventsInfo struct { + Topic string + StartHeight uint64 + EndHeight uint64 +} + +type FlowBlockInfo struct { + Id string + Height uint64 +} + +func EventsHandler(flowClient *client.Client) func(http.ResponseWriter, *http.Request) { + if flowClient == nil { + panic("Flow client is not set") + } + + return func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/events" { + http.Error(w, "404 not found.", http.StatusNotFound) + return + } + + if r.Method != "POST" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + return + } + + // Try to decode the request body into FlowEventsInfo the struct. + var eventsInfo FlowEventsInfo + err := decodeJSONBody(w, r, &eventsInfo) + if err != nil { + var mr *malformedRequest + if errors.As(err, &mr) { + http.Error(w, mr.msg, mr.status) + } else { + log.Println(err.Error()) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + return + } + + // Fetch Lock events + events, err := getLockEvents(flowClient, eventsInfo) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + + if len(events) == 0 { + w.Write([]byte("{\"result\":[]}")) + return + } + + js, err := json.Marshal(events) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + res := fmt.Sprintf("{\"result\":%s}", js) + w.Write([]byte(res)) + } +} + +func BlockHandler(flowClient *client.Client) func(http.ResponseWriter, *http.Request) { + if flowClient == nil { + panic("Flow client is not set") + } + + return func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/block" { + http.Error(w, "404 not found.", http.StatusNotFound) + return + } + + if r.Method != "POST" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + return + } + + // Try to decode the request body into FlowEventsInfo the struct. + var blockInfo FlowBlockInfo + err := decodeJSONBody(w, r, &blockInfo) + if err != nil { + var mr *malformedRequest + if errors.As(err, &mr) { + http.Error(w, mr.msg, mr.status) + } else { + log.Println(err.Error()) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + return + } + + // Fetch Block info + block, err := getBlock(flowClient, blockInfo) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + js, err := json.Marshal(block) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + res := fmt.Sprintf("{\"result\":%s}", js) + + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(res)) + } +} + +func LatestBlockNumberHandler(flowClient *client.Client) func(http.ResponseWriter, *http.Request) { + if flowClient == nil { + panic("Flow client is not set") + } + + return func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/latest_block_number" { + http.Error(w, "404 not found.", http.StatusNotFound) + return + } + + if r.Method != "POST" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + return + } + + // Fetch Latest sealed Flow block + latestBlock, err := getLatestBlock(flowClient) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + res := fmt.Sprintf("{\"result\":%d}", latestBlock.Height) + + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(res)) + } +} + +// getEnv get key environment variable if exist otherwise return defalutValue +func getEnv(key, defaultValue string) string { + value := os.Getenv(key) + if len(value) == 0 { + return defaultValue + } + return value +} + +func handleErr(err error) { + if err != nil { + panic(err) + } +} + +// 34944396, 34944396, "A.c8873a26b148ed14.Starport.Lock" +func main() { + // connect to Flow testnet + flowAccessURL := getEnv("FLOW_ACCESS_URL", "access.devnet.nodes.onflow.org:9000") + flowClient, err := client.New(flowAccessURL, grpc.WithInsecure()) + handleErr(err) + err = flowClient.Ping(context.Background()) + handleErr(err) + + // Add `Lock` and other Flow events handler + http.HandleFunc("/events", EventsHandler(flowClient)) + + // Add block handler + http.HandleFunc("/block", BlockHandler(flowClient)) + + // Add latest block handler + http.HandleFunc("/latest_block_number", LatestBlockNumberHandler(flowClient)) + + // Start the server + flowServerPort := getEnv("FLOW_SERVER_PORT", "8089") + fmt.Printf("Starting server at port %s\n", flowServerPort) + if err := http.ListenAndServe(":"+flowServerPort, nil); err != nil { + log.Fatal(err) + } +} diff --git a/flow/flow-fetcher/starport/flow_lock_event.go b/flow/flow-fetcher/starport/flow_lock_event.go new file mode 100644 index 000000000..69eee29af --- /dev/null +++ b/flow/flow-fetcher/starport/flow_lock_event.go @@ -0,0 +1,34 @@ +package starport + +import ( + "fmt" + + "github.com/onflow/cadence" + "github.com/onflow/flow-go-sdk" +) + +// pub event Lock(asset: String, recipient: Address?, amount: UFix64) +type FlowLockEvent cadence.Event + +func (evt FlowLockEvent) Asset() string { + return string(evt.Fields[0].(cadence.String)) +} + +func (evt FlowLockEvent) Recipient() *flow.Address { + optionalAddress := (evt.Fields[1]).(cadence.Optional) + if cadenceAddress, ok := optionalAddress.Value.(cadence.Address); ok { + recipientAddress := flow.BytesToAddress(cadenceAddress.Bytes()) + return &recipientAddress + } + return nil +} + +func (evt FlowLockEvent) Amount() uint64 { + // return float64(evt.Fields[2].(cadence.UFix64).ToGoValue().(uint64)) / 1e8 // ufixed 64 have 8 digits of precision + return evt.Fields[2].(cadence.UFix64).ToGoValue().(uint64) +} + +func (evt FlowLockEvent) String() string { + return fmt.Sprintf("Lock event: asset: %s, recipient: %s, amount: %d", + evt.Asset(), evt.Recipient(), evt.Amount()) +} diff --git a/flow/flow.json b/flow/flow.json new file mode 100644 index 000000000..cf686b9d9 --- /dev/null +++ b/flow/flow.json @@ -0,0 +1,31 @@ +{ + "emulators": { + "default": { + "port": 3569, + "serviceAccount": "emulator-account" + } + }, + "contracts": { + "Starport": "./cadence/contracts/Starport.cdc" + }, + "networks": { + "emulator": "127.0.0.1:3569", + "mainnet": "access.mainnet.nodes.onflow.org:9000", + "testnet": "access.devnet.nodes.onflow.org:9000" + }, + "accounts": { + "emulator-account": { + "address": "f8d6e0586b0a20c7", + "key": "4ee4450749579c24b6e051c4439608e8182ef255fc1fde4aada3c4c7563bc3dc" + }, + "my-testnet-account": { + "address": "c8873a26b148ed14", + "key": "3a47b62d3f777b59336f9ff949a79cb5bd4cfdce6a97e70559b267a1efc51b06" + } + }, + "deployments": { + "testnet": { + "my-testnet-account": ["Starport"] + } + } +} diff --git a/flow/test/README.md b/flow/test/README.md new file mode 100644 index 000000000..a34e2f633 --- /dev/null +++ b/flow/test/README.md @@ -0,0 +1,25 @@ +## About + +This is a Gateway Starport for the Flow blockchain. + +## Installation + +### Node _(optional if you have it installed already)_ + +Please follow instructions on NodeJS download page and install latest version of NodeJS software: +https://nodejs.org/en/download/ + +### Flow Emulator _(optional if you have it installed already)_ + +Flow Emulator is bundled with Flow CLI. You can find instructions on how to install it on Flow Docs site: +https://docs.onflow.org/flow-cli/ + +### Run tests + +`yarn install` + +`yarn test` + +### Afterword + +Good luck and happy hacking! :) diff --git a/flow/test/babel.config.json b/flow/test/babel.config.json new file mode 100644 index 000000000..394c5435b --- /dev/null +++ b/flow/test/babel.config.json @@ -0,0 +1,12 @@ +{ + "presets": [ + [ + "@babel/preset-env", + { + "targets": { + "node": "current" + } + } + ] + ] +} diff --git a/flow/test/flow.signer.js b/flow/test/flow.signer.js new file mode 100644 index 000000000..f67b55df4 --- /dev/null +++ b/flow/test/flow.signer.js @@ -0,0 +1,25 @@ +const EC = require("elliptic").ec; +const ec = new EC("secp256k1"); +//const ec = new EC("p256"); +const { SHA3 } = require("sha3"); + +const FLOW_TAG = [ + 70, 76, 79, 87, 45, 86, 48, 46, 48, 45, 117, 115, 101, 114, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +const hashMsg = (msgBytes) => { + const sha = new SHA3(256); + sha.update(Buffer.from(msgBytes)); + return sha.digest(); +}; + +export const signWithKey = (privateKey, message) => { + const key = ec.keyFromPrivate(Buffer.from(privateKey, "hex")); + const messageWithTag = FLOW_TAG.concat(message); + const sig = key.sign(hashMsg(messageWithTag)); + const n = 32; + const r = sig.r.toArrayLike(Buffer, "be", n); + const s = sig.s.toArrayLike(Buffer, "be", n); + return Buffer.concat([r, s]).toString("hex"); +}; diff --git a/flow/test/jest.config.js b/flow/test/jest.config.js new file mode 100644 index 000000000..5821148c4 --- /dev/null +++ b/flow/test/jest.config.js @@ -0,0 +1,5 @@ +module.exports = { + testEnvironment: "node", + verbose: true, + coveragePathIgnorePatterns: ["/node_modules/"], +}; diff --git a/flow/test/package.json b/flow/test/package.json new file mode 100644 index 000000000..1a07222e9 --- /dev/null +++ b/flow/test/package.json @@ -0,0 +1,26 @@ +{ + "name": "flow", + "version": "0.0.0", + "main": "index.js", + "license": "MIT", + "scripts": { + "init-flow": "flow init", + "start-emulator": "flow emulator start -v", + "test": "jest", + "format": "prettier --write '**/*.{ts,js,css,json,md}'" + }, + "dependencies": { + "@babel/core": "^7.12.10", + "@babel/preset-env": "^7.12.11", + "@onflow/types": "^0.0.4", + "babel-jest": "^27.0.6", + "elliptic": "^6.5.4", + "flow-js-testing": "^0.1.11", + "google-protobuf": "^3.14.0", + "jest": "^27.0.6", + "sha3": "^2.1.4" + }, + "devDependencies": { + "prettier": "^2.3.0" + } +} diff --git a/flow/test/starport.test.js b/flow/test/starport.test.js new file mode 100644 index 000000000..d56b7d9e0 --- /dev/null +++ b/flow/test/starport.test.js @@ -0,0 +1,729 @@ +import path from "path"; +import { + init, + sendTransaction, + deployContractByName, + getTransactionCode, + getContractAddress, + getAccountAddress, + mintFlow, + getScriptCode, + executeScript, +} from "flow-js-testing"; +import { + UFix64, + UInt256, + UInt8, + String as fString, + Array as fArray, + Address, +} from "@onflow/types"; +import { signWithKey } from "./flow.signer"; + +const basePath = path.resolve(__dirname, "../cadence"); +const STARPORT_CONTRACT_NAME = "Starport"; + +const AUTHORITIES_DATA = [ + { + publicKey: + "3668a8e41cfede2cbfd40dae4b22cff39c8795b53194b5a921d1d5d41fda370f26c37e4de564f780a95d6253e20e0866c5fe6b418b7ade867e2f1119a216716c", + privateKey: + "b3a88b1465c1f27b42485b8b178828ba34636d88b1edf2a45606d23872072454", + }, + { + publicKey: + "f1e35032c15c4107ab7e1e876236d8024b9db84e4f70605097987933179c730cb00f4b4b9961494d2b83b0573b179d1a9a7db7ab2e0517de3c41411a17b50f8e", + privateKey: + "c262abe9b55cdc2c3ca961583774fcefa25a0a36915bd8c48008c5951c938484", + }, +]; + +async function deployStarport() { + const deployer = await getAccountAddress(); // random address + + await mintFlow(deployer, "100.000000"); + + let result = await deployContractByName({ + name: STARPORT_CONTRACT_NAME, + to: deployer, + args: [], + }); + expect(result.errorMessage).toEqual(""); + return deployer; +} + +async function runTransaction(transactionFileName, starportDeployer, args) { + const addressMap = await getAddressMap(); + const signers = [starportDeployer]; + const code = await getTransactionCode({ + name: transactionFileName, + addressMap, + }); + return await sendTransaction({ code, args, signers }); +} + +async function getAddressMap() { + const Starport = await getContractAddress(STARPORT_CONTRACT_NAME); + return { + Starport, + }; +} + +async function prepareForUnlock(userName) { + const user = await getAccountAddress(userName); + const Alice = await getAccountAddress("Alice"); + + await deployStarport(); + + const address = await getAddressMap(); + + // Set supply caps + const newSupplyCap = "1000.0"; + await runTransaction("starport/set_supply_cap_admin", address.Starport, [ + [newSupplyCap, UFix64], + ]); + + // User deposits Flow token to Starport + await depositFlowTokens(user, "100.000000"); + + const authorities = [ + AUTHORITIES_DATA[0].publicKey, + AUTHORITIES_DATA[1].publicKey, + ]; + await runTransaction("starport/change_authorities_admin", address.Starport, [ + [authorities, fArray(fString)], + ]); +} + +async function getDataFromStarport(scriptName, args = []) { + const name = scriptName; + + // Generate addressMap from import statements + const Starport = await getContractAddress(STARPORT_CONTRACT_NAME); + + const addressMap = { + Starport, + }; + + let code = await getScriptCode({ + name, + addressMap, + }); + + const value = await executeScript({ + code, + args, + }); + return value; +} + +async function getLockedBalance() { + const name = "get_locked_balance"; + return getDataFromStarport(name); +} + +async function getAuthorities() { + const name = "get_authorities"; + return getDataFromStarport(name); +} + +async function getEraId() { + const name = "get_era_id"; + return getDataFromStarport(name); +} + +async function getFlowSupplyCap() { + const name = "get_flow_supply_cap"; + return getDataFromStarport(name); +} + +async function getAccountFlowBalance(userAddress) { + const name = "get_account_flow_balance"; + return getDataFromStarport(name, [[userAddress, Address]]); +} + +async function buildUnlockMessage( + noticeEraId, + noticeEraIndex, + parentNoticeHex, + toAddress, + amount +) { + const name = "build_unlock_message"; + return getDataFromStarport(name, [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentNoticeHex, fString], + [toAddress, Address], + [amount, UFix64], + ]); +} + +async function buildChangeAuthoritiesMessage( + noticeEraId, + noticeEraIndex, + parentNoticeHex, + newAuthorities +) { + const name = "build_change_authorities_message"; + return getDataFromStarport(name, [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentNoticeHex, fString], + [newAuthorities, fArray(fString)], + ]); +} + +async function buildSetSupplyCapMessage( + noticeEraId, + noticeEraIndex, + parentNoticeHex, + supplyCap +) { + const name = "build_set_supply_cap_message"; + return getDataFromStarport(name, [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentNoticeHex, fString], + [supplyCap, UFix64], + ]); +} + +async function depositFlowTokens(user, amount) { + // User mints Flow tokens + await mintFlow(user, amount); + + // User locks their Flow tokens in Starport + await runTransaction("starport/setup_starport_user", user, []); + const lockRes = await runTransaction("starport/lock_flow_tokens", user, [ + [amount, UFix64], + ]); + return lockRes; +} + +describe("Starport Tests", () => { + beforeAll(() => { + init(basePath); + }); + + test("# Deploy Starport", async () => { + await deployStarport(); + }); + + test("# Lock tokens", async () => { + await deployStarport(); + + const address = await getAddressMap(); + + // Set supply caps + const newSupplyCap = "1000.0"; + await runTransaction("starport/set_supply_cap_admin", address.Starport, [ + [newSupplyCap, UFix64], + ]); + + const Alice = await getAccountAddress("Alice"); + const aliceAmount = "100.000000"; + const Bob = await getAccountAddress("Bob"); + const bobAmount = "50.000000"; + + // Starport locked Flow balance is 0 at the beginning + const starportBalanceBefore = await getLockedBalance(); + expect(starportBalanceBefore).toEqual("0.00000000"); + + // Alice deposits Flow token to Starport + const aliceLockRes = await depositFlowTokens(Alice, aliceAmount); + + const aliceLockEvent = aliceLockRes.events[2].data; + expect(aliceLockEvent.recipient).toEqual(Alice); + expect(Number(aliceLockEvent.amount)).toEqual(100.0); + expect(aliceLockEvent.asset).toEqual("FLOW"); + + // Check Starport's Flow locked balance after Alice deposit + const starportBalanceWithAlice = await getLockedBalance(); + expect(Number(starportBalanceWithAlice)).toEqual(100.0); + + // Bob deposits Flow token to Starport + const bobLockRes = await depositFlowTokens(Bob, bobAmount); + + const bobLockEvent = bobLockRes.events[2].data; + expect(bobLockEvent.recipient).toEqual(Bob); + expect(Number(bobLockEvent.amount)).toEqual(50.0); + + // Check Starport's Flow locked balance after Alice deposit + const starportBalanceWithBob = await getLockedBalance(); + expect(Number(starportBalanceWithBob)).toEqual(150.0); + }); + + test("# Unlock tokens by notice", async () => { + // Prepare Starport for execting `Unlock` notice + await prepareForUnlock("Charlie"); + + const address = await getAddressMap(); + + const noticeEraId = 1; + const noticeEraIndex = 0; + const parentHex = ""; + + // Unlock tokens to the given address + const toAddress = "0xf3fcd2c1a78f5eee"; + const amount = "10.0"; + + const unlockMessage = await buildUnlockMessage( + noticeEraId, + noticeEraIndex, + parentHex, + toAddress, + amount + ); + // Sign the message with Authority 1 private key + const signature1 = signWithKey( + AUTHORITIES_DATA[0].privateKey, + unlockMessage + ); + // Sign the message with Authority 2 private key + const signature2 = signWithKey( + AUTHORITIES_DATA[1].privateKey, + unlockMessage + ); + const signatures = [signature1, signature2]; + + const userBalanceBefore = Number(await getAccountFlowBalance(toAddress)); + const unlockRes = await runTransaction( + "starport/unlock_flow_tokens_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [signatures, fArray(fString)], + [toAddress, Address], + [amount, UFix64], + ] + ); + + const unlockEvent = unlockRes.events[3].data; + + expect(Number(unlockEvent.amount)).toEqual(10.0); + expect(unlockEvent.account).toEqual(toAddress); + expect(unlockEvent.asset).toEqual("FLOW"); + + const balance = await getLockedBalance(); + expect(Number(balance)).toEqual(90.0); + + const userBalanceAfter = Number(await getAccountFlowBalance(toAddress)); + expect(userBalanceAfter - userBalanceBefore).toEqual(10.0); + + // Check `eraId` after notice was executed + const eraIdAfter = await getEraId(); + expect(eraIdAfter).toEqual(1); + }); + + test("# Unlock tokens by admin", async () => { + const Pete = await getAccountAddress("Pete"); + const Anna = await getAccountAddress("Anna"); + + await deployStarport(); + + const address = await getAddressMap(); + + // Set supply caps + const newSupplyCap = "1000.0"; + await runTransaction("starport/set_supply_cap_admin", address.Starport, [ + [newSupplyCap, UFix64], + ]); + + // Charlie deposits Flow token to Starport + await depositFlowTokens(Pete, "100.000000"); + + // Unlock tokens to Alice address + const toAddress = Anna; + const amount = "10.0"; + + const userBalanceBefore = Number(await getAccountFlowBalance(toAddress)); + const unlockRes = await runTransaction( + "starport/unlock_flow_tokens_admin", + address.Starport, + [ + [toAddress, Address], + [amount, UFix64], + ] + ); + + const unlockEvent = unlockRes.events[2].data; + + expect(Number(unlockEvent.amount)).toEqual(10.0); + expect(unlockEvent.account).toEqual(toAddress); + expect(unlockEvent.asset).toEqual("FLOW"); + + const balance = await getLockedBalance(); + expect(Number(balance)).toEqual(90.0); + + const userBalanceAfter = Number(await getAccountFlowBalance(toAddress)); + expect(userBalanceAfter - userBalanceBefore).toEqual(10.0); + }); + + test("# Change authorities by notice", async () => { + await deployStarport(); + + // Check authorities storage field + const authoritiesBefore = await getAuthorities(); + expect(authoritiesBefore).toEqual([]); + + const address = await getAddressMap(); + + const authorities = [ + AUTHORITIES_DATA[0].publicKey, + AUTHORITIES_DATA[1].publicKey, + ]; + await runTransaction( + "starport/change_authorities_admin", + address.Starport, + [[authorities, fArray(fString)]] + ); + + // Check authorities storage field + const authoritiesAdmin = await getAuthorities(); + expect(authoritiesAdmin).toEqual(authorities); + + const noticeEraId = 1; + const noticeEraIndex = 0; + const parentHex = ""; + + const newAuthorities = [ + "05df808dce3bf02d37990bd76a6e4deaaf5e29ac03677227d42b0d6914403d626256a30fb15d80da9aad7d2b22ffc5a8998043dcf86c38b3d03ea784a33d441a", + "b97f907e17fcc7cdb98fb8952afbe6c610d78e969336e3577190a10cf4629dc25398d737b67cb0249c8da8bf191ee36686aed9e8172fd90d397d704dc1110ae6", + ]; + + const changeAuthoritiesMessage = await buildChangeAuthoritiesMessage( + noticeEraId, + noticeEraIndex, + parentHex, + newAuthorities + ); + // Sign the message with Authority 1 private key + const signature1 = signWithKey( + AUTHORITIES_DATA[0].privateKey, + changeAuthoritiesMessage + ); + // Sign the message with Authority 2 private key + const signature2 = signWithKey( + AUTHORITIES_DATA[1].privateKey, + changeAuthoritiesMessage + ); + const signatures = [signature1, signature2]; + + const changeAuthoritiesRes = await runTransaction( + "starport/change_authorities_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [newAuthorities, fArray(fString)], + [signatures, fArray(fString)], + ] + ); + + let changeEvent = changeAuthoritiesRes.events[0].data; + expect(changeEvent.newAuthorities).toEqual(newAuthorities); + + // Check authorities storage field + const authoritiesAfter = await getAuthorities(); + expect(authoritiesAfter).toEqual(newAuthorities); + }); + + test("# Change authorities by admin", async () => { + await deployStarport(); + + const address = await getAddressMap(); + + // Check authorities storage field + const authoritiesBefore = await getAuthorities(); + expect(authoritiesBefore).toEqual([]); + + const authorities = [ + "6f39d97fbb1a537d154a999636a083e2f85bc6815b7599609eb50d50f534f7773ff29ccf13022ca039edfdb7b0efc79bcc766d5f989c67c009e14a6f0526b6aa", + "582e62e9a06541e66e7a1033b76e23c70d1520a42c6d7de97548a486942971969964e3e24aae3c88b58e2f4d1213302162b539a5e476d36f63904c82a87a07f2", + ]; + const authoritiesRes = await runTransaction( + "starport/change_authorities_admin", + address.Starport, + [[authorities, fArray(fString)]] + ); + + const changeEvent = authoritiesRes.events[0].data; + + expect(changeEvent.newAuthorities).toEqual(authorities); + + // Check authorities storage field + const authoritiesAfter = await getAuthorities(); + expect(authoritiesAfter).toEqual(authorities); + }); + + test("# Set supply cap by notice", async () => { + await deployStarport(); + + const address = await getAddressMap(); + + const authorities = [ + AUTHORITIES_DATA[0].publicKey, + AUTHORITIES_DATA[1].publicKey, + ]; + await runTransaction( + "starport/change_authorities_admin", + address.Starport, + [[authorities, fArray(fString)]] + ); + + // Check authorities storage field + const authoritiesAdmin = await getAuthorities(); + expect(authoritiesAdmin).toEqual(authorities); + + const noticeEraId = 1; + const noticeEraIndex = 0; + const parentHex = ""; + const newSupplyCap = "1000.0"; + + const setSupplyCapMessage = await buildSetSupplyCapMessage( + noticeEraId, + noticeEraIndex, + parentHex, + newSupplyCap + ); + // Sign the message with Authority 1 private key + const signature1 = signWithKey( + AUTHORITIES_DATA[0].privateKey, + setSupplyCapMessage + ); + // Sign the message with Authority 2 private key + const signature2 = signWithKey( + AUTHORITIES_DATA[1].privateKey, + setSupplyCapMessage + ); + const signatures = [signature1, signature2]; + + const setSupplyCapRes = await runTransaction( + "starport/set_supply_cap_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [newSupplyCap, UFix64], + [signatures, fArray(fString)], + ] + ); + + const supplyCapEvent = setSupplyCapRes.events[0].data; + + expect(supplyCapEvent.asset).toEqual("FLOW"); + expect(Number(supplyCapEvent.supplyCap)).toEqual(Number(newSupplyCap)); + + const setSupplyCap = await getFlowSupplyCap(); + expect(Number(setSupplyCap)).toEqual(Number(newSupplyCap)); + }); + + test("# Set supply cap by admin", async () => { + await deployStarport(); + + const address = await getAddressMap(); + + const supplyCap = await getFlowSupplyCap(); + expect(Number(supplyCap)).toEqual(0.0); + + const newSupplyCap = "100.0"; + const supplyCapRes = await runTransaction( + "starport/set_supply_cap_admin", + address.Starport, + [[newSupplyCap, UFix64]] + ); + + const supplyCapEvent = supplyCapRes.events[0].data; + expect(supplyCapEvent.asset).toEqual("FLOW"); + expect(Number(supplyCapEvent.supplyCap)).toEqual(100.0); + + const setSupplyCap = await getFlowSupplyCap(); + expect(Number(setSupplyCap)).toEqual(Number(newSupplyCap)); + }); + + test("# Set supply cap and lock tokens", async () => { + await deployStarport(); + + const address = await getAddressMap(); + + const supplyCap = await getFlowSupplyCap(); + expect(Number(supplyCap)).toEqual(0.0); + + const newSupplyCap = "100.0"; + await runTransaction("starport/set_supply_cap_admin", address.Starport, [ + [newSupplyCap, UFix64], + ]); + + // An attempt to deposit more than supply cap allows + const Sofia = await getAccountAddress("Sofia"); + const sofiaAmount = "150.000000"; + + // Alice deposits Flow token to Starport + try { + await depositFlowTokens(Sofia, sofiaAmount); + } catch (err) { + expect(err.includes("Supply Cap Exceeded")).toBeTruthy(); + } + expect.hasAssertions(); + }); + + test("# Notice validation error, already invoked", async () => { + // Prepare Starport for execting `Unlock` notice + await prepareForUnlock("Scott"); + + const address = await getAddressMap(); + + const noticeEraId = 1; + const noticeEraIndex = 0; + const parentHex = ""; + // Unlock tokens to the given address + const toAddress = "0xf3fcd2c1a78f5eee"; + const amount = "10.0"; + + const unlockMessage = await buildUnlockMessage( + noticeEraId, + noticeEraIndex, + parentHex, + toAddress, + amount + ); + // Sign the message with Authority 1 private key + const signature1 = signWithKey( + AUTHORITIES_DATA[0].privateKey, + unlockMessage + ); + // Sign the message with Authority 2 private key + const signature2 = signWithKey( + AUTHORITIES_DATA[1].privateKey, + unlockMessage + ); + const signatures = [signature1, signature2]; + + await runTransaction( + "starport/unlock_flow_tokens_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [signatures, fArray(fString)], + [toAddress, Address], + [amount, UFix64], + ] + ); + + // An attempt to execute the same notice twice + const unlockErrRes = await runTransaction( + "starport/unlock_flow_tokens_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [signatures, fArray(fString)], + [toAddress, Address], + [amount, UFix64], + ] + ); + // Check emitted error + const unlockErrEvent = unlockErrRes.events[0].data; + expect(unlockErrEvent.noticeEraId).toEqual(noticeEraId); + expect(unlockErrEvent.noticeEraIndex).toEqual(noticeEraIndex); + expect(unlockErrEvent.error).toEqual("Notice replay"); + }); + + test("# Notice validation error, invalid signatures", async () => { + // Prepare Starport for execting `Unlock` notice + await prepareForUnlock("Adam"); + + const address = await getAddressMap(); + + const noticeEraId = 1; + const noticeEraIndex = 0; + const parentHex = ""; + // Unlock tokens to the given address + const toAddress = "0xf3fcd2c1a78f5eee"; + const amount = "10.0"; + const signatures = [ + "d8661ebbbe0cc415063a6027fadf6d78b883b88f0ea3b7a15d839b126aa85b55b273e2aeb777a07d04288b432897409e50d4cbadb28f4cf072c5bd3b9220d30e", + "f01e292593ef04dacc9d35090182b831197fbae7b900585d822b901aa05df75ff505e167a3e2504cc2a0bd928507eaa3e81b9dfbd6878ec9d2e121f0b69537c8", + ]; + + const unlockRes = await runTransaction( + "starport/unlock_flow_tokens_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [signatures, fArray(fString)], + [toAddress, Address], + [amount, UFix64], + ] + ); + + const unlockErrEvent = unlockRes.events[0].data; + expect(unlockErrEvent.noticeEraId).toEqual(noticeEraId); + expect(unlockErrEvent.noticeEraIndex).toEqual(noticeEraIndex); + expect(unlockErrEvent.error).toEqual("Signatures are incorrect"); + }); + + test("# Notice validation error, invalid era", async () => { + // Prepare Starport for execting `Unlock` notice + await prepareForUnlock("Emily"); + + const address = await getAddressMap(); + + const noticeEraId = 3; + const noticeEraIndex = 0; + const parentHex = ""; + // Unlock tokens to the given address + const toAddress = "0x179b6b1cb6755e31"; + const amount = "10.0"; + + const unlockMessage = await buildUnlockMessage( + noticeEraId, + noticeEraIndex, + parentHex, + toAddress, + amount + ); + // Sign the message with Authority 1 private key + const signature1 = signWithKey( + AUTHORITIES_DATA[0].privateKey, + unlockMessage + ); + // Sign the message with Authority 2 private key + const signature2 = signWithKey( + AUTHORITIES_DATA[1].privateKey, + unlockMessage + ); + const signatures = [signature1, signature2]; + + const unlockErrRes = await runTransaction( + "starport/unlock_flow_tokens_notice", + address.Starport, + [ + [noticeEraId, UInt256], + [noticeEraIndex, UInt256], + [parentHex, fString], + [signatures, fArray(fString)], + [toAddress, Address], + [amount, UFix64], + ] + ); + + // Check emitted error + const unlockErrEvent = unlockErrRes.events[0].data; + expect(unlockErrEvent.noticeEraId).toEqual(noticeEraId); + expect(unlockErrEvent.noticeEraIndex).toEqual(noticeEraIndex); + expect(unlockErrEvent.error).toEqual( + "Notice must use existing era or start next era" + ); + }); +}); diff --git a/gateway-crypto/src/no_std.rs b/gateway-crypto/src/no_std.rs index 305b5c95b..a0a2e0cdd 100644 --- a/gateway-crypto/src/no_std.rs +++ b/gateway-crypto/src/no_std.rs @@ -199,6 +199,31 @@ pub fn eth_hash_string(eth_hash: &[u8; 32]) -> String { format!("0x{}", hex::encode(eth_hash)) } +pub fn flow_addr_str_to_address(address_str: &str) -> Option<[u8; 8]> { + if address_str.len() == 18 && &address_str[0..2] == "0x" { + if let Ok(bytes) = hex::decode(&address_str[2..18]) { + if let Ok(flow_address) = bytes.try_into() { + return Some(flow_address); + } + } + } + return None; +} + +pub fn flow_asset_str_to_address(asset_str: &str) -> Option<[u8; 8]> { + if asset_str.len() <= 8 { + let mut flow_asset: [u8; 8] = [0; 8]; + for (i, elem) in asset_str.as_bytes().iter().enumerate() { + flow_asset[i] = *elem; + if i == 7 { + break; + } + } + return Some(flow_asset); + } + return None; +} + #[cfg(test)] mod test { use super::*; diff --git a/node/src/cli.rs b/node/src/cli.rs index bc748b735..a8612a913 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -11,6 +11,10 @@ pub struct GatewayCmd { #[structopt(long = "eth-rpc-url")] pub eth_rpc_url: Option, + /// Set the Flow Server Url for interfacing with Flow fetch server + #[structopt(long = "flow-server-url")] + pub flow_server_url: Option, + /// Set the miner address (only useful for validator) #[structopt(long = "miner")] pub miner: Option, diff --git a/node/src/command.rs b/node/src/command.rs index 7d27d803c..f2947b849 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -136,6 +136,7 @@ pub fn run() -> sc_cli::Result<()> { runtime_interfaces::initialize_validator_config( cli.gateway.eth_key_id.clone(), cli.gateway.eth_rpc_url.clone(), + cli.gateway.flow_server_url.clone(), cli.gateway.miner.clone(), cli.gateway.opf_url.clone(), ); diff --git a/pallets/cash/Cargo.toml b/pallets/cash/Cargo.toml index d75b846ec..ba731e71b 100644 --- a/pallets/cash/Cargo.toml +++ b/pallets/cash/Cargo.toml @@ -44,6 +44,7 @@ pallet-timestamp = { default-features = false, git = 'https://github.com/compoun pallet-oracle = { path = '../oracle', default-features = false } runtime-interfaces = { path = '../runtime-interfaces', default-features = false } ethereum-client = { path = '../../ethereum-client', default-features = false } +flow-client = { path = '../../flow-client', default-features = false } gateway-crypto = { path = '../../gateway-crypto', default-features = false } trx-request = { path = '../../trx-request', default-features = false } our-std = { path = '../../our-std', default-features = false } diff --git a/pallets/cash/src/chains.rs b/pallets/cash/src/chains.rs index a5228c719..10ed05bdc 100644 --- a/pallets/cash/src/chains.rs +++ b/pallets/cash/src/chains.rs @@ -1,5 +1,6 @@ use codec::{Decode, Encode}; use ethereum_client::{EthereumBlock, EthereumEvent}; +use flow_client::{FlowBlock, FlowEvent}; use gateway_crypto::public_key_bytes_to_eth_address; use our_std::vec::Vec; use our_std::{ @@ -25,6 +26,7 @@ pub enum ChainId { Gate, Eth, Dot, + Flow, } impl ChainId { @@ -33,6 +35,7 @@ impl ChainId { ChainId::Gate => Ok(ChainAccount::Gate(Gateway::str_to_address(addr)?)), ChainId::Eth => Ok(ChainAccount::Eth(Ethereum::str_to_address(addr)?)), ChainId::Dot => Ok(ChainAccount::Dot(Polkadot::str_to_address(addr)?)), + ChainId::Flow => Ok(ChainAccount::Flow(Flow::str_to_address(addr)?)), } } @@ -41,6 +44,7 @@ impl ChainId { ChainId::Gate => Err(Reason::Unreachable), ChainId::Eth => Ok(ChainAsset::Eth(Ethereum::str_to_address(addr)?)), ChainId::Dot => Err(Reason::NotImplemented), + ChainId::Flow => Ok(ChainAsset::Flow(Flow::asset_str_to_address(addr)?)), } } @@ -49,6 +53,7 @@ impl ChainId { ChainId::Gate => Ok(ChainHash::Gate(Gateway::str_to_hash(hash)?)), ChainId::Eth => Ok(ChainHash::Eth(Ethereum::str_to_hash(hash)?)), ChainId::Dot => Ok(ChainHash::Dot(Polkadot::str_to_hash(hash)?)), + ChainId::Flow => Err(Reason::NotImplemented), } } @@ -57,6 +62,7 @@ impl ChainId { ChainId::Gate => Ok(ChainAccount::Gate(::signer_address()?)), ChainId::Eth => Ok(ChainAccount::Eth(::signer_address()?)), ChainId::Dot => Ok(ChainAccount::Dot(::signer_address()?)), + ChainId::Flow => Err(Reason::NotImplemented), } } @@ -65,6 +71,7 @@ impl ChainId { ChainId::Gate => ChainHash::Gate(::hash_bytes(data)), ChainId::Eth => ChainHash::Eth(::hash_bytes(data)), ChainId::Dot => ChainHash::Dot(::hash_bytes(data)), + ChainId::Flow => ChainHash::Flow(::hash_bytes(data)), } } @@ -79,6 +86,7 @@ impl ChainId { ChainId::Dot => Ok(ChainSignature::Dot(::sign_message( message, )?)), + ChainId::Flow => Err(Reason::NotImplemented), } } @@ -87,6 +95,7 @@ impl ChainId { ChainId::Gate => ChainHash::Gate(::zero_hash()), ChainId::Eth => ChainHash::Eth(::zero_hash()), ChainId::Dot => ChainHash::Dot(::zero_hash()), + ChainId::Flow => ChainHash::Flow(::zero_hash()), } } } @@ -100,6 +109,7 @@ pub enum ChainAccount { Gate(::Address), Eth(::Address), Dot(::Address), + Flow(::Address), } impl ChainAccount { @@ -108,6 +118,7 @@ impl ChainAccount { ChainAccount::Gate(_) => ChainId::Gate, ChainAccount::Eth(_) => ChainId::Eth, ChainAccount::Dot(_) => ChainId::Dot, + ChainAccount::Flow(_) => ChainId::Flow, } } } @@ -134,6 +145,7 @@ impl From for String { ChainAccount::Gate(_) => String::from("GATE"), // XXX ChainAccount::Eth(address) => format!("ETH:0x{}", hex::encode(address)), ChainAccount::Dot(_) => String::from("DOT"), // XXX + ChainAccount::Flow(address) => format!("FLOW:0x{}", hex::encode(address)), } } } @@ -144,6 +156,7 @@ pub enum ChainAsset { Gate(Reserved), Eth(::Address), Dot(Reserved), + Flow(::Address), } // For serialize (which we don't really use, but are required to implement) @@ -153,6 +166,7 @@ impl ChainAsset { ChainAsset::Gate(_) => ChainId::Gate, ChainAsset::Eth(_) => ChainId::Eth, ChainAsset::Dot(_) => ChainId::Dot, + ChainAsset::Flow(_) => ChainId::Flow, } } } @@ -178,6 +192,7 @@ impl From for String { ChainAsset::Gate(_) => String::from("GATE"), // XXX ChainAsset::Eth(address) => format!("ETH:0x{}", hex::encode(address)), ChainAsset::Dot(_) => String::from("DOT"), // XXX + ChainAsset::Flow(name) => format!("FLOW:0x{}", hex::encode(name)), } } } @@ -225,6 +240,7 @@ pub enum ChainHash { Gate(::Hash), Eth(::Hash), Dot(::Hash), + Flow(::Hash), } // Display so we can format local storage keys. @@ -234,6 +250,7 @@ impl our_std::fmt::Display for ChainHash { ChainHash::Gate(gate_hash) => write!(f, "GATE#{:X?}", gate_hash), ChainHash::Eth(eth_hash) => write!(f, "ETH#{:X?}", eth_hash), ChainHash::Dot(dot_hash) => write!(f, "DOT#{:X?}", dot_hash), + ChainHash::Flow(flow_hash) => write!(f, "FLOW#{:X?}", flow_hash), } } } @@ -259,6 +276,7 @@ impl From for String { ChainHash::Gate(_) => format!("GATE"), // XXX ChainHash::Eth(eth_hash) => ::hash_string(ð_hash), ChainHash::Dot(_) => format!("DOT"), // XXX + ChainHash::Flow(_) => format!("FLOW"), } } } @@ -338,6 +356,7 @@ impl FromStr for ChainId { match s.to_ascii_uppercase().as_str() { "ETH" => Ok(ChainId::Eth), "DOT" => Ok(ChainId::Dot), + "FLOW" => Ok(ChainId::Flow), _ => Err(Reason::BadChainId), } } @@ -348,39 +367,52 @@ impl FromStr for ChainId { #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, Types)] pub enum ChainBlock { Eth(::Block), + Flow(::Block), } impl ChainBlock { pub fn chain_id(&self) -> ChainId { match self { ChainBlock::Eth(_) => ChainId::Eth, + ChainBlock::Flow(_) => ChainId::Flow, } } pub fn hash(&self) -> ChainHash { match self { ChainBlock::Eth(block) => ChainHash::Eth(block.hash), + ChainBlock::Flow(block) => ChainHash::Flow(block.blockId), } } pub fn parent_hash(&self) -> ChainHash { match self { ChainBlock::Eth(block) => ChainHash::Eth(block.parent_hash), + ChainBlock::Flow(block) => ChainHash::Flow(block.parentBlockId), } } pub fn number(&self) -> ChainBlockNumber { match self { ChainBlock::Eth(block) => block.number, + ChainBlock::Flow(block) => block.height, } } - pub fn events(&self) -> impl Iterator + '_ { + pub fn events(&self) -> Box + '_> { match self { - ChainBlock::Eth(block) => block - .events - .iter() - .map(move |e| ChainBlockEvent::Eth(block.number, e.clone())), + ChainBlock::Eth(block) => Box::new( + block + .events + .iter() + .map(move |e| ChainBlockEvent::Eth(block.number, e.clone())), + ), + ChainBlock::Flow(block) => Box::new( + block + .events + .iter() + .map(move |e| ChainBlockEvent::Flow(block.height, e.clone())), + ), } } } @@ -389,30 +421,37 @@ impl ChainBlock { #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, Types)] pub enum ChainBlocks { Eth(Vec<::Block>), + Flow(Vec<::Block>), } impl ChainBlocks { pub fn chain_id(&self) -> ChainId { match self { ChainBlocks::Eth(_) => ChainId::Eth, + ChainBlocks::Flow(_) => ChainId::Flow, } } pub fn len(&self) -> usize { match self { ChainBlocks::Eth(blocks) => blocks.len(), + ChainBlocks::Flow(blocks) => blocks.len(), } } - pub fn blocks(&self) -> impl Iterator + '_ { + pub fn blocks(&self) -> Box + '_> { match self { - ChainBlocks::Eth(blocks) => blocks.iter().map(|b| ChainBlock::Eth(b.clone())), + ChainBlocks::Eth(blocks) => Box::new(blocks.iter().map(|b| ChainBlock::Eth(b.clone()))), + ChainBlocks::Flow(blocks) => { + Box::new(blocks.iter().map(|b| ChainBlock::Flow(b.clone()))) + } } } - pub fn block_numbers(&self) -> impl Iterator + '_ { + pub fn block_numbers(&self) -> Box + '_> { match self { - ChainBlocks::Eth(blocks) => blocks.iter().map(|b| b.number), + ChainBlocks::Eth(blocks) => Box::new(blocks.iter().map(|b| b.number)), + ChainBlocks::Flow(blocks) => Box::new(blocks.iter().map(|b| b.height)), } } @@ -433,6 +472,17 @@ impl ChainBlocks { }) .collect(), ), + ChainBlocks::Flow(blocks) => ChainBlocks::Flow( + blocks + .into_iter() + .filter(|block| { + !pending_blocks.iter().any(|t| { + t.block.hash() == ChainHash::Flow(block.blockId) + && t.has_supporter(signer) + }) + }) + .collect(), + ), } } } @@ -441,6 +491,7 @@ impl From for ChainBlocks { fn from(block: ChainBlock) -> Self { match block { ChainBlock::Eth(block) => ChainBlocks::Eth(vec![block]), + ChainBlock::Flow(block) => ChainBlocks::Flow(vec![block]), } } } @@ -593,6 +644,7 @@ impl ChainReorgTally { pub enum ChainBlockEvent { Reserved, Eth(ChainBlockNumber, ::Event), + Flow(ChainBlockNumber, ::Event), } impl ChainBlockEvent { @@ -600,6 +652,7 @@ impl ChainBlockEvent { match self { ChainBlockEvent::Reserved => panic!("reserved"), ChainBlockEvent::Eth(..) => ChainId::Eth, + ChainBlockEvent::Flow(..) => ChainId::Flow, } } @@ -607,6 +660,7 @@ impl ChainBlockEvent { match self { ChainBlockEvent::Reserved => panic!("reserved"), ChainBlockEvent::Eth(block_num, _) => *block_num, + ChainBlockEvent::Flow(block_num, _) => *block_num, } } @@ -620,6 +674,7 @@ impl ChainBlockEvent { pub enum ChainBlockEvents { Reserved, Eth(Vec<(ChainBlockNumber, ::Event)>), + Flow(Vec<(ChainBlockNumber, ::Event)>), } impl ChainBlockEvents { @@ -629,6 +684,7 @@ impl ChainBlockEvents { ChainId::Gate => Err(Reason::Unreachable), ChainId::Eth => Ok(ChainBlockEvents::Eth(vec![])), ChainId::Dot => Err(Reason::NotImplemented), + ChainId::Flow => Ok(ChainBlockEvents::Flow(vec![])), } } @@ -637,6 +693,7 @@ impl ChainBlockEvents { match self { ChainBlockEvents::Reserved => panic!("reserved"), ChainBlockEvents::Eth(eth_block_events) => eth_block_events.len(), + ChainBlockEvents::Flow(flow_block_events) => flow_block_events.len(), } } @@ -650,6 +707,17 @@ impl ChainBlockEvents { eth_block_events.push((eth_block.number, event.clone())); } } + // Added to make it compile, doesn't look good + ChainBlock::Flow(_) => panic!("unreachable"), + }, + ChainBlockEvents::Flow(flow_block_events) => match block { + ChainBlock::Flow(flow_block) => { + for event in flow_block.events.iter() { + flow_block_events.push((flow_block.height, event.clone())); + } + } + // Added to make it compile, doesn't look good + ChainBlock::Eth(_) => panic!("unreachable"), }, } } @@ -664,6 +732,9 @@ impl ChainBlockEvents { ChainBlockEvents::Eth(eth_block_events) => { eth_block_events.retain(|(b, e)| f(&ChainBlockEvent::Eth(*b, e.clone()))); } + ChainBlockEvents::Flow(flow_block_events) => { + flow_block_events.retain(|(b, e)| f(&ChainBlockEvent::Flow(*b, e.clone()))); + } } } @@ -676,6 +747,16 @@ impl ChainBlockEvents { ChainBlockEvent::Eth(block_num, eth_block) => eth_block_events .iter() .position(|(b, e)| *b == *block_num && *e == *eth_block), + // Added to make it compile, doesn't look good + ChainBlockEvent::Flow(_, _) => panic!("unreachable"), + }, + ChainBlockEvents::Flow(flow_block_events) => match event { + ChainBlockEvent::Reserved => panic!("unreachable"), + ChainBlockEvent::Flow(block_num, flow_block) => flow_block_events + .iter() + .position(|(b, e)| *b == *block_num && *e == *flow_block), + // Added to make it compile, doesn't look good + ChainBlockEvent::Eth(_, _) => panic!("unreachable"), }, } } @@ -687,6 +768,9 @@ impl ChainBlockEvents { ChainBlockEvents::Eth(eth_block_events) => { eth_block_events.remove(pos); } + ChainBlockEvents::Flow(flow_block_events) => { + flow_block_events.remove(pos); + } } } } @@ -715,6 +799,7 @@ pub trait Chain { fn sign_message(message: &[u8]) -> Result; fn signer_address() -> Result; fn str_to_address(addr: &str) -> Result; + fn asset_str_to_address(addr: &str) -> Result; fn address_string(address: &Self::Address) -> String; fn str_to_hash(hash: &str) -> Result; fn hash_string(hash: &Self::Hash) -> String; @@ -729,6 +814,9 @@ pub struct Ethereum {} #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)] pub struct Polkadot {} +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)] +pub struct Flow {} + impl Chain for Gateway { const ID: ChainId = ChainId::Gate; @@ -798,6 +886,10 @@ impl Chain for Gateway { panic!("XXX not implemented"); } + fn asset_str_to_address(_addr: &str) -> Result { + panic!("XXX not implemented"); + } + fn address_string(_address: &Self::Address) -> String { panic!("XXX not implemented"); } @@ -899,6 +991,11 @@ impl Chain for Ethereum { } } + // No need for this method, `str_to_address` is used for th asset + fn asset_str_to_address(_addr: &str) -> Result { + panic!("XXX not implemented"); + } + fn address_string(address: &Self::Address) -> String { gateway_crypto::eth_address_string(address) } @@ -979,6 +1076,97 @@ impl Chain for Polkadot { panic!("XXX not implemented"); } + fn asset_str_to_address(_addr: &str) -> Result { + panic!("XXX not implemented"); + } + + fn address_string(_address: &Self::Address) -> String { + panic!("XXX not implemented"); + } + + fn str_to_hash(_hash: &str) -> Result { + panic!("XXX not implemented"); + } + + fn hash_string(_hash: &Self::Hash) -> String { + panic!("XXX not implemented"); + } +} + +impl Chain for Flow { + const ID: ChainId = ChainId::Flow; + + #[type_alias("Flow__Chain__")] + type Address = [u8; 8]; + + #[type_alias("Flow__Chain__")] + type Amount = u128; + + #[type_alias("Flow__Chain__")] + type CashIndex = u128; + + #[type_alias("Flow__Chain__")] + type Rate = u128; + + #[type_alias("Flow__Chain__")] + type Timestamp = u64; + + #[type_alias("Flow__Chain__")] + type Hash = [u8; 32]; + + #[type_alias("Flow__Chain__")] + type PublicKey = (); + + #[type_alias("Flow__Chain__")] + type Signature = (); + + #[type_alias("Flow__Chain__")] + type Event = FlowEvent; + + #[type_alias("Flow__Chain__")] + type Block = FlowBlock; + + fn zero_hash() -> Self::Hash { + [0u8; 32] + } + + fn hash_bytes(_data: &[u8]) -> Self::Hash { + panic!("XXX not implemented"); + } + + fn recover_user_address( + _data: &[u8], + _signature: Self::Signature, + ) -> Result { + panic!("XXX not implemented"); + } + + fn recover_address(_data: &[u8], _signature: Self::Signature) -> Result { + panic!("XXX not implemented"); + } + + fn sign_message(_message: &[u8]) -> Result { + panic!("XXX not implemented"); + } + + fn signer_address() -> Result { + panic!("XXX not implemented"); + } + + fn str_to_address(addr: &str) -> Result { + match gateway_crypto::flow_addr_str_to_address(addr) { + Some(s) => Ok(s), + None => Err(Reason::BadAddress), + } + } + + fn asset_str_to_address(addr: &str) -> Result { + match gateway_crypto::flow_asset_str_to_address(addr) { + Some(s) => Ok(s), + None => Err(Reason::BadAddress), + } + } + fn address_string(_address: &Self::Address) -> String { panic!("XXX not implemented"); } diff --git a/pallets/cash/src/core.rs b/pallets/cash/src/core.rs index edafa5235..81218e35f 100644 --- a/pallets/cash/src/core.rs +++ b/pallets/cash/src/core.rs @@ -314,6 +314,21 @@ pub fn apply_chain_event_internal(event: &ChainBlockEvent) -> Result< result.to_vec(), ), }, + ChainBlockEvent::Flow(_block_num, flow_event) => match flow_event { + flow_client::FlowEvent::Lock { + asset, + // sender, + // chain, + recipient, + amount, + } => internal::lock::lock_internal::( + internal::assets::get_asset::(ChainAsset::Flow(*asset))?, + ChainAccount::Flow(*recipient), + ChainAccount::Flow(*recipient), + // chains::get_chain_account(chain.to_string(), *recipient)?, + internal::assets::get_quantity::(ChainAsset::Flow(*asset), *amount)?, + ), + }, } } @@ -351,6 +366,8 @@ pub fn unapply_chain_event_internal(event: &ChainBlockEvent) -> Resul _ => Ok(()), }, + // XXX toni - not sure it's needed for Flow, since there are no reorgs + ChainBlockEvent::Flow(_block_num, _flow_event) => panic!("not implemented"), } } diff --git a/pallets/cash/src/events.rs b/pallets/cash/src/events.rs index 573ee6ec6..8c8423985 100644 --- a/pallets/cash/src/events.rs +++ b/pallets/cash/src/events.rs @@ -1,10 +1,13 @@ use crate::{ - chains::{Chain, ChainAccount, ChainBlock, ChainBlockNumber, ChainBlocks, ChainId, Ethereum}, + chains::{ + Chain, ChainAccount, ChainBlock, ChainBlockNumber, ChainBlocks, ChainId, Ethereum, Flow, + }, debug, reason::Reason, }; use codec::{Decode, Encode}; use ethereum_client::{EthereumBlock, EthereumClientError}; +use flow_client::{FlowBlock, FlowClientError}; use our_std::RuntimeDebug; use types_derive::Types; @@ -14,7 +17,9 @@ pub enum EventError { NoRpcUrl, NoStarportAddress, EthereumClientError(EthereumClientError), + FlowClientError(FlowClientError), ErrorDecodingHex, + NoFlowServerUrl, } /// Fetch a block from the underlying chain. @@ -28,6 +33,11 @@ pub fn fetch_chain_block( (ChainId::Eth, ChainAccount::Eth(eth_starport_address)) => { Ok(fetch_eth_block(number, ð_starport_address).map(ChainBlock::Eth)?) } + (ChainId::Flow, ChainAccount::Flow(flow_starport_address)) => Ok(fetch_flow_block( + number, + &hex::encode(&flow_starport_address), + ) + .map(ChainBlock::Flow)?), (ChainId::Dot, _) => Err(Reason::Unreachable), _ => Err(Reason::Unreachable), } @@ -45,6 +55,11 @@ pub fn fetch_chain_blocks( (ChainId::Eth, ChainAccount::Eth(eth_starport_address)) => { Ok(fetch_eth_blocks(from, to, ð_starport_address)?) } + (ChainId::Flow, ChainAccount::Flow(flow_starport_address)) => Ok(fetch_flow_blocks( + from, + to, + &hex::encode(&flow_starport_address), + )?), (ChainId::Dot, _) => Err(Reason::Unreachable), _ => Err(Reason::Unreachable), } @@ -87,6 +102,45 @@ fn fetch_eth_blocks( Ok(ChainBlocks::Eth(acc)) } +// Fetch a single block from the Flow Starport. +fn fetch_flow_block( + number: ChainBlockNumber, + flow_starport_address: &str, +) -> Result { + debug!("Fetching Flow Block {}", number); + let flow_server_url = runtime_interfaces::validator_config_interface::get_flow_server_url() + .ok_or(EventError::NoFlowServerUrl)?; + // TODO XXX Find a way to move topic out of here + let flow_block = + flow_client::get_block(&flow_server_url, flow_starport_address, number, "Lock") + .map_err(EventError::FlowClientError)?; + Ok(flow_block) +} + +/// Fetch blocks from the Flow Starport, return up to `slack` blocks to add to the event queue. +fn fetch_flow_blocks( + from: ChainBlockNumber, + to: ChainBlockNumber, + flow_starport_address: &str, +) -> Result { + debug!("Fetching Flow Blocks [{}-{})", from, to); + let mut acc: Vec<::Block> = vec![]; + for block_number in from..to { + match fetch_flow_block(block_number, flow_starport_address) { + Ok(block) => { + acc.push(block); + } + Err(EventError::FlowClientError(FlowClientError::NoResult)) => { + break; // done + } + Err(err) => { + return Err(err); + } + } + } + Ok(ChainBlocks::Flow(acc)) +} + #[cfg(test)] mod tests { use crate::events::*; @@ -135,6 +189,9 @@ mod tests { assert_eq!(actual.number, expected.number); } } + ChainBlocks::Flow(_) => { + assert!(false) + } } }); diff --git a/pallets/cash/src/internal/events.rs b/pallets/cash/src/internal/events.rs index 77452614e..cc25f5f58 100644 --- a/pallets/cash/src/internal/events.rs +++ b/pallets/cash/src/internal/events.rs @@ -81,16 +81,19 @@ pub fn risk_adjusted_value( _ => Ok(Quantity::new(0, USD)), }, + _ => return Err(Reason::Unreachable), } } /// Incrementally perform the next step of tracking events from all the underlying chains. pub fn track_chain_events() -> Result<(), Reason> { let mut lock = StorageLock::