Skip to content

Commit

Permalink
feat: Use Asset + Chain on API's (#4153)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel <daniel@chainflip.io>
Co-authored-by: Andrew Dibble <andrew@chainflip.io>
  • Loading branch information
3 people authored Nov 3, 2023
1 parent e10d14a commit 7996039
Show file tree
Hide file tree
Showing 29 changed files with 581 additions and 576 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions api/bin/chainflip-broker-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ name = "chainflip-broker-api"
[dependencies]
chainflip-api = { path = "../../lib" }
cf-utilities = { package = "utilities", path = "../../../utilities" }
custom-rpc = { path = "../../../state-chain/custom-rpc" }

anyhow = "1.0.66"
clap = { version = "3.2.23", features = ["derive"] }
Expand Down
88 changes: 34 additions & 54 deletions api/bin/chainflip-broker-api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,19 @@

Exposes Broker functionality via a json api interface.

## Example

> ✋ Note: This example assumes that the node that is exposing the statechain rpc is funded.
```sh
> ./target/release/chainflip-broker-api \
--state_chain.ws_endpoint=ws://localhost:9944 \
--state_chain.signing_key_file /path/to/my/signing_key \
--port 62378 # or whatever port you want to use

🎙 Server is listening on 0.0.0.0:62378.
```

Then in another terminal:

```sh
# This method might not be necessary/useful depending on how we set up the broker.
> curl -H "Content-Type: application/json" \
-d '{"id":1, "jsonrpc":"2.0", "method": "broker_registerAccount"}' \
http://localhost:62378

{"jsonrpc":"2.0","result":null,"id":1}

# This method take a little while to respond because it submits and waits for finality. So make sure the request doesn't block.
# Parameters are: [source_asset, destination_asset, destination_address, broker_commission].
> curl -H "Content-Type: application/json" \
-d '{"id":1, "jsonrpc":"2.0", "method": "broker_requestSwapDepositAddress", "params": ["Eth", "Flip","0xabababababababababababababababababababab", 0]}' \
http://localhost:62378

# The result is the hex-encoded deposit address, expiry block, and the issued block.
{"jsonrpc":"2.0","result":{"address":"0x4ef7608893d5a06c2689b8d15b4dc400be0954f2",expiry_block:12345},"id":1}

# This request also accepts cross chain message metadata as an optional fifth parameter:
{"gas_budget":"0x1000", message:[0,1,2,3,4], cf_parameters: [], source_address: "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", source_chain: "Bitcoin"}
```
> For detailed instructions on how to configure and use the API please refer to the [Chainflip Docs](https://docs.chainflip.io/integration/swapping-and-aggregation/running-a-broker/broker-api).
## Command line arguments and defaults

- The `state_chain.ws_endpoint` should point at a synced rpc node. The default is `ws://localhost:9944`.
- The `state_chain.signing_key_file` should be the broker's private key for their on-chain account. The account should be funded. The default is `/etc/chainflip/keys/signing_key_file`.
- The `port` is the port on which the broker will listen for connections. Use 0 to assign a random port. The default is 80.

```sh
> ./target/release/chainflip-broker-api --help
```bash copy
./target/release/chainflip-broker-api --help
```

```sh
chainflip-broker-api

USAGE:
Expand All @@ -68,31 +36,43 @@ OPTIONS:
The state chain node's rpc endpoint. [default: ws://localhost:9944]
```

## Rpc Methods

### `broker_requestSwapDepositAddress`
## Example

Parameters:
> ✋ Note: This example assumes that the node that is exposing the statechain rpc is funded.
- Source asset as a camel-case string, eg "Eth" or "Dot".
- Egress asset as a camel-case string, eg "Eth" or "Dot".
- Egress Address in hex. Must match the format of the egress asset's chain: 20 bytes for ethereum assets, 32 bytes for polkadot.
- Broker Commission in basis points (100th of a percent).
1. Run the Broker API server with the following command:

Return:
```bash copy
./target/release/chainflip-broker-api \
--state_chain.ws_endpoint=ws://localhost:9944 \
--state_chain.signing_key_file /path/to/my/signing_key \
--port 62378 # or whatever port you want to use
```
It will print `🎙 Server is listening on 0.0.0.0:62378.` and continue to run.

- Hex-encoded deposit address.
2. Then in another terminal:
Register your account as a broker if you are not already.

### `broker_registerAccount`
```bash copy
curl -H "Content-Type: application/json" \
-d '{"id":1, "jsonrpc":"2.0", "method": "broker_register_account"}' \
http://localhost:62378
```

Parameters:
Returns `{"jsonrpc":"2.0","result":null,"id":1}`

None
3. Request a swap deposit address

Return:
This method may take a little while to respond because it submits and waits for finality. So make sure the request doesn't block.

- null if successful, otherwise an error.
```bash copy
curl -H "Content-Type: application/json" \
-d '{"id":1, "jsonrpc":"2.0", "method": "broker_request_swap_deposit_address", "params": ["Eth", "Flip","0xabababababababababababababababababababab", 0]}' \
http://localhost:62378
```

## Limitations
The result is the hex-encoded deposit address, expiry block, and the issued block:

- Doesn't seem to work with `wss`, so make sure the address is specified with `ws`. Should be ok since we're not going to expose this externally.
```json
{"jsonrpc":"2.0","result":{"address":"0xe720e23f62efc931d465a9d16ca303d72ad6c0bc","issued_block":5418,"channel_id":6,"source_chain_expiry_block":2954},"id":1}
```
1 change: 1 addition & 0 deletions api/bin/chainflip-broker-api/clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
too-many-arguments-threshold = 100
14 changes: 8 additions & 6 deletions api/bin/chainflip-broker-api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ use cf_utilities::{
};
use chainflip_api::{
self, clean_foreign_chain_address,
primitives::{AccountRole, Asset, BasisPoints, BlockNumber, CcmChannelMetadata, ChannelId},
primitives::{AccountRole, BasisPoints, BlockNumber, CcmChannelMetadata, ChannelId},
settings::StateChain,
BrokerApi, OperatorApi, StateChainApi,
};
use clap::Parser;
use custom_rpc::RpcAsset;
use futures::FutureExt;
use jsonrpsee::{core::async_trait, proc_macros::rpc, server::ServerBuilder};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -46,8 +47,8 @@ pub trait Rpc {
#[method(name = "request_swap_deposit_address", aliases = ["broker_requestSwapDepositAddress"])]
async fn request_swap_deposit_address(
&self,
source_asset: Asset,
destination_asset: Asset,
source_asset: RpcAsset,
destination_asset: RpcAsset,
destination_address: String,
broker_commission_bps: BasisPoints,
channel_metadata: Option<CcmChannelMetadata>,
Expand Down Expand Up @@ -83,17 +84,18 @@ impl RpcServer for RpcServerImpl {

async fn request_swap_deposit_address(
&self,
source_asset: Asset,
destination_asset: Asset,
source_asset: RpcAsset,
destination_asset: RpcAsset,
destination_address: String,
broker_commission_bps: BasisPoints,
channel_metadata: Option<CcmChannelMetadata>,
) -> Result<BrokerSwapDepositAddress, AnyhowRpcError> {
let destination_asset = destination_asset.try_into()?;
Ok(self
.api
.broker_api()
.request_swap_deposit_address(
source_asset,
source_asset.try_into()?,
destination_asset,
clean_foreign_chain_address(destination_asset.into(), &destination_address)?,
broker_commission_bps,
Expand Down
1 change: 1 addition & 0 deletions api/bin/chainflip-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ chainflip-engine = { path = "../../../engine/" }
chainflip-api = { path = "../../lib" }
cf-chains = { path = "../../../state-chain/chains" }
utilities = { path = "../../../utilities" }
custom-rpc = { path = "../../../state-chain/custom-rpc" }

[build-dependencies]
substrate-build-script-utils = { git = "https://github.com/chainflip-io/substrate.git", tag = 'chainflip-monthly-2023-08+2' }
17 changes: 12 additions & 5 deletions api/bin/chainflip-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![feature(absolute_path)]
use anyhow::{Context, Result};
use clap::Parser;
use custom_rpc::RpcAsset;
use futures::FutureExt;
use serde::Serialize;
use std::{io::Write, path::PathBuf, sync::Arc};
Expand Down Expand Up @@ -57,13 +58,17 @@ async fn run_cli() -> Result<()> {
let api = StateChainApi::connect(scope, cli_settings.state_chain).await?;
match command_line_opts.cmd {
Broker(BrokerSubcommands::RequestSwapDepositAddress(params)) => {
let destination_asset =
RpcAsset::try_from((params.destination_asset, params.destination_chain))?
.try_into()?;
let SwapDepositAddress { address, .. } = api
.broker_api()
.request_swap_deposit_address(
params.source_asset,
params.destination_asset,
RpcAsset::try_from((params.source_asset, params.source_chain))?
.try_into()?,
destination_asset,
chainflip_api::clean_foreign_chain_address(
params.destination_asset.into(),
destination_asset.into(),
&params.destination_address,
)?,
params.broker_commission,
Expand All @@ -73,9 +78,11 @@ async fn run_cli() -> Result<()> {
println!("Deposit Address: {address}");
},
LiquidityProvider(
LiquidityProviderSubcommands::RequestLiquidityDepositAddress { asset },
LiquidityProviderSubcommands::RequestLiquidityDepositAddress { asset, chain },
) => {
let address = api.lp_api().request_liquidity_deposit_address(asset).await?;
let asset = RpcAsset::try_from((asset, chain))?;
let address =
api.lp_api().request_liquidity_deposit_address(asset.try_into()?).await?;
println!("Deposit Address: {address}");
},
LiquidityProvider(
Expand Down
12 changes: 9 additions & 3 deletions api/bin/chainflip-cli/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ impl Default for CLICommandLineOptions {

#[derive(Parser, Clone, Debug)]
pub struct SwapRequestParams {
/// Source asset ("eth"|"dot")
/// Source asset ("ETH"|"DOT")
pub source_asset: Asset,
/// Egress asset ("eth"|"dot")
/// Egress asset ("ETH"|"DOT")
pub destination_asset: Asset,
// Note: we delay parsing this into `ForeignChainAddress`
// until we know which kind of address to expect (based
Expand All @@ -73,6 +73,10 @@ pub struct SwapRequestParams {
pub destination_address: String,
/// Commission to the broker in basis points
pub broker_commission: u16,
/// Chain of the source asset ("Ethereum"|"Polkadot")
pub source_chain: Option<ForeignChain>,
/// Chain of the destination asset ("Ethereum"|"Polkadot")
pub destination_chain: Option<ForeignChain>,
}

#[derive(clap::Subcommand, Clone, Debug)]
Expand All @@ -85,8 +89,10 @@ pub enum BrokerSubcommands {
pub enum LiquidityProviderSubcommands {
/// Request a liquidity deposit address.
RequestLiquidityDepositAddress {
/// Asset to deposit.
/// Asset to deposit ("ETH"|"DOT")
asset: Asset,
/// Chain of the deposit asset ("Ethereum"|"Polkadot")
chain: Option<ForeignChain>,
},
/// Register an Liquidity Refund Address for the given chain. An address must be
/// registered to request a deposit address for the given chain.
Expand Down
1 change: 1 addition & 0 deletions api/bin/chainflip-lp-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3.3", features = ["env-filter"] }
pallet-cf-pools = { path = '../../../state-chain/pallets/cf-pools' }
cf-primitives = { path = "../../../state-chain/primitives" }
custom-rpc = { path = "../../../state-chain/custom-rpc" }

# Local
chainflip-api = { path = "../../lib" }
Expand Down
Loading

0 comments on commit 7996039

Please sign in to comment.