设置客户端 (Setting up a client)
设置 SDK 客户端 (Setting up an SDK client)
一旦 sdk 被导入到项目中,就可以用它来与 Namada 区块链交互。假设我们有一个节点在 IP 和端口 127.0.0.1:26657
上运行,我们想向网络发送一个交易。
SDK 可能用于各种目的,但在这个示例中,我们将使用它向网络发送一个交易。
首先,我们需要实现 Client
,以便我们能够与正在运行的节点通信。
use reqwest::{Client, Response as ClientResponse};
pub struct SdkClient {
url: String,
client: Client,
}
impl SdkClient {
pub fn new(url: String) -> Self {
Self {
client: Client::new(),
url,
}
}
pub async fn post(&self, body: String) -> Result<ClientResponse, reqwest::Error> {
self.client
.post(format!("http://{}", &self.url))
.body(body)
.send()
.await
}
}
这使我们能够使用来自 reqwest
(一个外部库)的 Client
向网络发送交易。
我们还需要定义一些客户端将用于与网络交互的函数。
#[async_trait::async_trait]
impl ClientTrait for SdkClient {
type Error = Error;
async fn request(
&self,
path: String,
data: Option<Vec<u8>>,
height: Option<BlockHeight>,
prove: bool,
) -> Result<EncodedResponseQuery, Self::Error> {
let data = data.unwrap_or_default();
let height = height
.map(|height| {
tendermint::block::Height::try_from(height.0)
.map_err(|_err| Error::InvalidHeight(height))
})
.transpose()?;
let response = self
.abci_query(
Some(std::str::FromStr::from_str(&path).unwrap()),
data,
height,
prove,
)
.await?;
match response.code {
Code::Ok => Ok(EncodedResponseQuery {
data: response.value,
info: response.info,
proof: response.proof,
}),
Code::Err(code) => Err(Error::Query(response.info, code)),
}
}
async fn perform<R>(&self, request: R) -> Result<R::Response, tm_rpc::Error>
where
R: tm_rpc::SimpleRequest,
{
let request_body = request.into_json();
let response = self.post(request_body).await;
match response {
Ok(response) => {
let response_json = response.text().await.unwrap();
R::Response::from_string(response_json)
}
Err(e) => {
let error_msg = e.to_string();
Err(tm_rpc::Error::server(error_msg))
}
}
}
}
现在,我们已经准备好使用这个客户端发送交易了。
Last updated