Building a Candy Store
In this section we will improve the GumballMachine by building a CandyStore. Start by changing the struct and impl names to CandyStore.
Next we are going to change the struct. First, instead of one Vault, we want a collection of Vaults, one for each token type. Since token names and symbols can actually clash, let's go the safe route and map between the token's address and the corresponding vault as shown by candy_vaults. Similarly the candy prices, which can be different for each candy vault, are kept in a map between the token address and the price.
1
struct CandyStore {
2
// token address mapped to vault holding that token
3
candy_vaults: HashMap<Address, Vault>,
4
5
collected_xrd: Vault,
6
7
// token address mapped to the price in XRD for that token
8
prices: HashMap<Address, Decimal>
9
}
10
11
impl CandyStore {
12
pub fn new() -> Component {
13
Self {
14
candy_vaults: HashMap::new(),
15
collected_xrd: Vault::new(RADIX_TOKEN),
16
prices: HashMap::new()
17
}
18
.instantiate()
19
}
Copied!
We also updated the new() function as shown above making it super simple. We construct the component with no active vaults or prices. In a moment we will add a method to add those dynamically.
Comment out the get_price and buy_gumball methods. You can now publish and test what we have so far to make sure it works.

Stocking the store

Now let's write the method that adds candy to the candy store and update the prices.
1
pub fn stock_candy(&mut self, candy: Bucket, new_price: Decimal) {
2
let candy_addr: Address = candy.resource_address();
3
4
// We can write assertions. If it fails, the whole transaction is safely rolled back.
5
// Here, we make sure that the provided bucket does not contain XRD
6
// and that the price is greater than zero.
7
assert!(candy_addr != self.collected_xrd.resource_address(), "cannot stock XRD as candy");
8
assert!(new_price > 0.into(), "new price must be a positive value");
9
10
// Try to find the vault with candy_addr as key.
11
// If it does not exist, it creates a new empty vault.
12
let vault = self.candy_vaults.entry(candy_addr).or_insert(Vault::new(candy_addr));
13
14
// Insert the candies in the vault
15
vault.put(candy);
16
17
// Update the price
18
self.prices.insert(candy_addr, new_price);
19
}
Copied!
Line 12 handles two cases. If the candy_addr is present in the candy_vaults keys, then we get back the vault from the HashMap. Otherwise we insert a new empty vault into the HashMap that is prepared to receive tokens. In both cases we then add the candy bucket to the vault on the next line. We also update the price whether or not it has a price already.

Querying the Candy Store

Next let's uncomment the get_price method and update it as shown.
1
pub fn get_price(&self, candy_addr: Address) {
2
// Make sure the candy_addr is not XRD
3
assert!(candy_addr != self.collected_xrd.resource_address(), "XRD is priceless");
4
5
// Display the price if present, display error otherwise
6
match self.prices.get(&candy_addr) {
7
Some(price) => info!("Price: {}", price),
8
None => info!("Could not find candy in stock !")
9
};
10
}
Copied!
Let's write a menu method that shows what candies are available in the store. An easy way to do that is to return an array of empty buckets for each candy we have in store. This makes all candy resource definitions show up in the current account's resources. After calling menu, the user can use the resim show [account_address] command to get the name, symbol and other metadata of each given token.
1
pub fn menu(&self) -> Vec<Bucket> {
2
let mut buckets = Vec::new();
3
for (_addr, vault) in self.candy_vaults.iter() {
4
buckets.push(vault.take(0));
5
}
6
buckets
7
}
Copied!
Does this make sense? If not then you might want to look into Vec (short for Vector) which is Rust's version of a dynamic array. Also note that the iter() method allows us to loop through the elements of our candy_vaults HashMap.
Did you notice that _addr has a leading underline character? This is used to let the compiler know that you are aware that this value is not actually used elsewhere in the method. Without the underline you will get a warning from the compiler.
This method has a small problem. It will return a bucket for a vault even if it doesn't have enough candy available to fulfill a minimal buy request of 1 item. How would you fix that? (Hint: vaults have a method named amount() that returns the number of tokens they hold.) Another thing you might want to try is to make a similar method called free_sample that returns a tiny portion of every candy in the store. It could return 1 candy of a selected type. Playing around with different possibilities like this is the quickest way to get comfortable with the design, code and test cycle and improve your Scrypto skills.

Buying Some Candy

To cap off this component's transformation we will improve the buy_gumball method. We will add a parameter allowing the user to specify which candy to buy. To keep things simple we will only buy one candy at a time, but you can easily extend this logic to handle different purchase quantities if you like.
1
pub fn buy_candy(&mut self, candy_addr: Address, payment: Bucket) -> (Bucket, Bucket) {
2
// take our price in XRD out of the payment
3
// if the caller has sent too few, or sent something other than XRD, they'll get a runtime error
4
let price = match self.prices.get(&candy_addr) {
5
Some(price) => price,
6
None => {
7
info!("Candy not in stock !");
8
std::process::abort()
9
}
10
};
11
12
self.collected_xrd.put(payment.take(*price));
13
14
let candy_bucket: Bucket = match self.candy_vaults.get(&candy_addr) {
15
Some(vault) => vault.take(1),
16
None => {
17
info!("Candy not in stock !");
18
std::process::abort()
19
}
20
};
21
22
(candy_bucket, payment)
23
}
Copied!
Other than the fact that we are grabbing the vault and the price from the respective HashMaps, this method is conceptually unchanged from the GumballMachine version.
So there you have it. We took a simple toy example and made the first steps towards turning it into something that might work in the real world. Still there is a major shortcoming. We cannot yet grab the proceeds from selling the candies. Before adding that we first have to learn how to secure our components to make methods only callable by specific people. We address this topic in the next chapter.
Copy link
Edit on GitHub
Contents