Skip to content

Commit 1df2fbd

Browse files
authored
chore!: documented all the builders. API changes (#39)
* Documented all the builder methods across the entire library. * Added examples for all the top-level functions. (78 documentation examples in total) * A few small changes to improve API (sponsor_by_faucet doesn't need an extra argument, allowed to specify gas and deposit for init call during deploy, accept BlockReference as Into)
1 parent 65d4b8c commit 1df2fbd

File tree

15 files changed

+1323
-106
lines changed

15 files changed

+1323
-106
lines changed

examples/nft.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ async fn main() {
88
let network = near_workspaces::sandbox().await.unwrap();
99
let nft = network.dev_create_account().await.unwrap();
1010
let account = network.dev_create_account().await.unwrap();
11+
let account2 = network.dev_create_account().await.unwrap();
1112
let network = NetworkConfig::from(network);
1213

1314
let nft_signer = Signer::new(Signer::from_workspace(&nft)).unwrap();
@@ -65,7 +66,7 @@ async fn main() {
6566
println!("Account has {}", tokens.data.first().unwrap().token_id);
6667

6768
Tokens::account(account.id().clone())
68-
.send_to(nft.id().clone())
69+
.send_to(account2.id().clone())
6970
.nft(nft.id().clone(), "1".to_string())
7071
.unwrap()
7172
.with_signer(nft_signer.clone())
@@ -83,13 +84,13 @@ async fn main() {
8384

8485
assert!(tokens.data.is_empty());
8586

86-
let tokens = Tokens::account(nft.id().clone())
87+
let tokens = Tokens::account(account2.id().clone())
8788
.nft_assets(nft.id().clone())
8889
.unwrap()
8990
.fetch_from(&network)
9091
.await
9192
.unwrap();
9293

9394
assert_eq!(tokens.data.len(), 1);
94-
println!("nft has {}", tokens.data.first().unwrap().token_id);
95+
println!("account 2 has {}", tokens.data.first().unwrap().token_id);
9596
}

src/account/create.rs

+31-5
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ pub struct CreateAccountBuilder {
2222
}
2323

2424
impl CreateAccountBuilder {
25+
/// Create an NEAR account and fund it by your own
26+
///
27+
/// You can only create an sub-account of your own account or sub-account of the linkdrop account ([near](https://nearblocks.io/address/near) on mainnet , [testnet](https://testnet.nearblocks.io/address/testnet) on testnet)
2528
pub fn fund_myself(
2629
self,
2730
signer_account_id: AccountId,
@@ -85,13 +88,14 @@ impl CreateAccountBuilder {
8588
}))
8689
}
8790

88-
pub fn sponsor_by_faucet_service(
89-
self,
90-
account_id: AccountId,
91-
) -> PublicKeyProvider<CreateAccountByFaucet, Infallible> {
91+
/// Create an account sponsored by faucet service
92+
///
93+
/// This is a way to create an account without having to fund it. It works only on testnet.
94+
/// You can only create an sub-account of the [testnet](https://testnet.nearblocks.io/address/testnet) account
95+
pub fn sponsor_by_faucet_service(self) -> PublicKeyProvider<CreateAccountByFaucet, Infallible> {
9296
PublicKeyProvider::new(Box::new(move |public_key| {
9397
Ok(CreateAccountByFaucet {
94-
new_account_id: account_id,
98+
new_account_id: self.account_id,
9599
public_key,
96100
})
97101
}))
@@ -105,11 +109,24 @@ pub struct CreateAccountByFaucet {
105109
}
106110

107111
impl CreateAccountByFaucet {
112+
/// Sends the account creation request to the default testnet faucet service.
113+
///
114+
/// The account will be created as a sub-account of the [testnet](https://testnet.nearblocks.io/address/testnet) account
108115
pub async fn send_to_testnet_faucet(self) -> Result<Response, FaucetError> {
109116
let testnet = NetworkConfig::testnet();
110117
self.send_to_config_faucet(&testnet).await
111118
}
112119

120+
/// Sends the account creation request to the faucet service specified in the network config.
121+
/// This way you can specify your own faucet service.
122+
///
123+
/// The function sends the request in the following format:
124+
/// ```json
125+
/// {
126+
/// "newAccountId": "new_account_id",
127+
/// "newAccountPublicKey": "new_account_public_key"
128+
/// }
129+
/// ```
113130
pub async fn send_to_config_faucet(
114131
self,
115132
config: &NetworkConfig,
@@ -122,6 +139,15 @@ impl CreateAccountByFaucet {
122139
self.send_to_faucet(faucet_service_url).await
123140
}
124141

142+
/// Sends the account creation request to the faucet service specified by the URL.
143+
///
144+
/// The function sends the request in the following format:
145+
/// ```json
146+
/// {
147+
/// "newAccountId": "new_account_id",
148+
/// "newAccountPublicKey": "new_account_public_key"
149+
/// }
150+
/// ```
125151
pub async fn send_to_faucet(self, url: &Url) -> Result<Response, FaucetError> {
126152
let mut data = std::collections::HashMap::new();
127153
data.insert("newAccountId", self.new_account_id.to_string());

src/account/mod.rs

+180
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ mod create;
3434
pub struct Account(pub AccountId);
3535

3636
impl Account {
37+
/// Prepares a query to fetch the [Data](crate::Data)<[AccountView](near_primitives::views::AccountView)> with the account information for the given account ID.
38+
///
39+
/// ## Example
40+
/// ```rust,no_run
41+
/// use near_api::*;
42+
///
43+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
44+
/// let account_info = Account("alice.testnet".parse()?).view().fetch_from_testnet().await?;
45+
/// println!("Account: {:?}", account_info);
46+
/// # Ok(())
47+
/// # }
48+
/// ```
3749
pub fn view(&self) -> QueryBuilder<AccountViewHandler> {
3850
let request = near_primitives::views::QueryRequest::ViewAccount {
3951
account_id: self.0.clone(),
@@ -45,6 +57,23 @@ impl Account {
4557
)
4658
}
4759

60+
/// Prepares a query to fetch the [Data](crate::Data)<[AccessKeyView](near_primitives::views::AccessKeyView)> with the access key information for the given account public key.
61+
///
62+
/// ## Example
63+
/// ```rust,no_run
64+
/// use near_api::*;
65+
/// use near_crypto::PublicKey;
66+
/// use std::str::FromStr;
67+
///
68+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
69+
/// let access_key = Account("alice.testnet".parse()?)
70+
/// .access_key(PublicKey::from_str("ed25519:H4sIAAAAAAAAA+2X0Q6CMBAAtVlJQgYAAAA=")?)
71+
/// .fetch_from_testnet()
72+
/// .await?;
73+
/// println!("Access key: {:?}", access_key);
74+
/// # Ok(())
75+
/// # }
76+
/// ```
4877
pub fn access_key(&self, signer_public_key: PublicKey) -> QueryBuilder<AccessKeyHandler> {
4978
let request = near_primitives::views::QueryRequest::ViewAccessKey {
5079
account_id: self.0.clone(),
@@ -57,6 +86,18 @@ impl Account {
5786
)
5887
}
5988

89+
/// Prepares a query to fetch the [AccessKeyList](near_primitives::views::AccessKeyList) list of access keys for the given account ID.
90+
///
91+
/// ## Example
92+
/// ```rust,no_run
93+
/// use near_api::*;
94+
///
95+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
96+
/// let access_keys = Account("alice.testnet".parse()?).list_keys().fetch_from_testnet().await?;
97+
/// println!("Access keys: {:?}", access_keys);
98+
/// # Ok(())
99+
/// # }
100+
/// ```
60101
pub fn list_keys(&self) -> QueryBuilder<AccessKeyListHandler> {
61102
let request = near_primitives::views::QueryRequest::ViewAccessKeyList {
62103
account_id: self.0.clone(),
@@ -68,6 +109,25 @@ impl Account {
68109
)
69110
}
70111

112+
/// Adds a new access key to the given account ID.
113+
///
114+
/// ## Example
115+
/// ```rust,no_run
116+
/// use near_api::*;
117+
/// use near_primitives::account::AccessKeyPermission;
118+
/// use near_crypto::PublicKey;
119+
/// use std::str::FromStr;
120+
///
121+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
122+
/// let pk = PublicKey::from_str("ed25519:H4sIAAAAAAAAA+2X0Q6CMBAAtVlJQgYAAAA=")?;
123+
/// let result: near_primitives::views::FinalExecutionOutcomeView = Account("alice.testnet".parse()?)
124+
/// .add_key(AccessKeyPermission::FullAccess, pk)
125+
/// .with_signer(Signer::new(Signer::from_ledger())?)
126+
/// .send_to_testnet()
127+
/// .await?;
128+
/// # Ok(())
129+
/// # }
130+
/// ```
71131
pub fn add_key(
72132
&self,
73133
permission: AccessKeyPermission,
@@ -84,6 +144,22 @@ impl Account {
84144
)
85145
}
86146

147+
/// Deletes an access key from the given account ID.
148+
///
149+
/// ## Example
150+
/// ```rust,no_run
151+
/// use near_api::*;
152+
/// use near_crypto::PublicKey;
153+
/// use std::str::FromStr;
154+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
155+
/// let result: near_primitives::views::FinalExecutionOutcomeView = Account("alice.testnet".parse()?)
156+
/// .delete_key(PublicKey::from_str("ed25519:H4sIAAAAAAAAA+2X0Q6CMBAAtVlJQgYAAAA=")?)
157+
/// .with_signer(Signer::new(Signer::from_ledger())?)
158+
/// .send_to_testnet()
159+
/// .await?;
160+
/// # Ok(())
161+
/// # }
162+
/// ```
87163
pub fn delete_key(&self, public_key: PublicKey) -> ConstructTransaction {
88164
ConstructTransaction::new(self.0.clone(), self.0.clone()).add_action(
89165
near_primitives::transaction::Action::DeleteKey(Box::new(DeleteKeyAction {
@@ -92,6 +168,23 @@ impl Account {
92168
)
93169
}
94170

171+
/// Deletes multiple access keys from the given account ID.
172+
///
173+
/// ## Example
174+
/// ```rust,no_run
175+
/// use near_api::*;
176+
/// use near_crypto::PublicKey;
177+
/// use std::str::FromStr;
178+
///
179+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
180+
/// let result: near_primitives::views::FinalExecutionOutcomeView = Account("alice.testnet".parse()?)
181+
/// .delete_keys(vec![PublicKey::from_str("ed25519:H4sIAAAAAAAAA+2X0Q6CMBAAtVlJQgYAAAA=")?])
182+
/// .with_signer(Signer::new(Signer::from_ledger())?)
183+
/// .send_to_testnet()
184+
/// .await?;
185+
/// # Ok(())
186+
/// # }
187+
/// ```
95188
pub fn delete_keys(&self, public_keys: Vec<PublicKey>) -> ConstructTransaction {
96189
let actions = public_keys
97190
.into_iter()
@@ -105,6 +198,27 @@ impl Account {
105198
ConstructTransaction::new(self.0.clone(), self.0.clone()).add_actions(actions)
106199
}
107200

201+
/// Deletes the account with the given beneficiary ID. The account balance will be transfered to the beneficiary.
202+
///
203+
/// Please note that this action is irreversible. Also, you have to understand that another person could potentially
204+
/// re-create the account with the same name and pretend to be you on other websites that use your account ID as a unique identifier.
205+
/// (near.social, devhub proposal, etc)
206+
///
207+
/// Do not use it unless you understand the consequences.
208+
///
209+
/// ## Example
210+
/// ```rust,no_run
211+
/// use near_api::*;
212+
///
213+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
214+
/// let result: near_primitives::views::FinalExecutionOutcomeView = Account("alice.testnet".parse()?)
215+
/// .delete_account_with_beneficiary("bob.testnet".parse()?)
216+
/// .with_signer(Signer::new(Signer::from_ledger())?)
217+
/// .send_to_testnet()
218+
/// .await?;
219+
/// # Ok(())
220+
/// # }
221+
/// ```
108222
pub fn delete_account_with_beneficiary(
109223
&self,
110224
beneficiary_id: AccountId,
@@ -116,6 +230,72 @@ impl Account {
116230
)
117231
}
118232

233+
/// Creates a new account builder for the given account ID.
234+
///
235+
/// ## Creating account sponsored by faucet service
236+
///
237+
/// This is a way to create an account without having to fund it. It works only on testnet.
238+
/// The account should be created as a sub-account of the [testnet](https://testnet.nearblocks.io/address/testnet) account
239+
///
240+
/// ```rust,no_run
241+
/// use near_api::*;
242+
///
243+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
244+
/// let secret = near_api::signer::generate_secret_key()?;
245+
/// let result: reqwest::Response = Account::create_account("alice.testnet".parse()?)
246+
/// .sponsor_by_faucet_service()
247+
/// .public_key(secret.public_key())?
248+
/// .send_to_testnet_faucet()
249+
/// .await?;
250+
/// // You have to save the secret key somewhere safe
251+
/// std::fs::write("secret.key", secret.to_string())?;
252+
/// # Ok(())
253+
/// # }
254+
/// ```
255+
///
256+
/// ## Creating sub-account of the linkdrop root account funded by your own NEAR and signed by your account
257+
///
258+
/// There is a few linkdrop root accounts that you can use to create sub-accounts.
259+
/// * For mainnet, you can use the [near](https://explorer.near.org/accounts/near) account.
260+
/// * For testnet, you can use the [testnet](https://testnet.nearblocks.io/address/testnet) account.
261+
///
262+
/// ```rust,no_run
263+
/// use near_api::*;
264+
///
265+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
266+
/// let secret = near_api::signer::generate_secret_key()?;
267+
/// let bob_signer = Signer::new(Signer::from_seed_phrase("lucky barrel fall come bottom can rib join rough around subway cloth ", None)?)?;
268+
/// let result: near_primitives::views::FinalExecutionOutcomeView = Account::create_account("alice.testnet".parse()?)
269+
/// .fund_myself("bob.testnet".parse()?, NearToken::from_near(1))
270+
/// .public_key(secret.public_key())?
271+
/// .with_signer(bob_signer)
272+
/// .send_to_testnet()
273+
/// .await?;
274+
/// # Ok(())
275+
/// # }
276+
/// ```
277+
///
278+
/// ## Creating sub-account of your own account funded by your NEAR
279+
///
280+
/// You can create only one level deep of sub-accounts.
281+
///
282+
/// E.g you are `alice.testnet`, you can't create `sub.sub.alice.testnet`, but you can create `sub.alice.testnet`.
283+
/// Though, 'sub.alice.testnet' can create sub-accounts of its own.
284+
/// ```rust,no_run
285+
/// use near_api::*;
286+
///
287+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
288+
/// let secret = near_api::signer::generate_secret_key()?;
289+
/// let bob_signer = Signer::new(Signer::from_seed_phrase("lucky barrel fall come bottom can rib join rough around subway cloth ", None)?)?;
290+
/// let result: near_primitives::views::FinalExecutionOutcomeView = Account::create_account("subaccount.bob.testnet".parse()?)
291+
/// .fund_myself("bob.testnet".parse()?, NearToken::from_near(1))
292+
/// .public_key(secret.public_key())?
293+
/// .with_signer(bob_signer)
294+
/// .send_to_testnet()
295+
/// .await?;
296+
/// # Ok(())
297+
/// # }
298+
/// ```
119299
pub const fn create_account(account_id: AccountId) -> CreateAccountBuilder {
120300
CreateAccountBuilder { account_id }
121301
}

0 commit comments

Comments
 (0)