Cadence Cookbook

Contribute

Admin Resource

Admin Resource

01 Apr 2022

Contributed by Flow Blockchain

Intermediate

Using an admin resource to have exclusive access to functions in a smart contract.

Smart Contract Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 //above is more code from the SetAndSeries Contract... pub resource Admin { pub fun addSeries(seriesId: UInt32, metadata: {String: String}) { pre { SetAndSeries.series[seriesId] == nil: "Cannot add Series: The Series already exists" } // Create the new Series var newSeries <- create Series( seriesId: seriesId, metadata: metadata ) // Add the new Series resource to the Series dictionary in the contract SetAndSeries.series[seriesId] <-! newSeries } pub fun borrowSeries(seriesId: UInt32): &Series { pre { SetAndSeries.series[seriesId] != nil: "Cannot borrow Series: The Series does not exist" } // Get a reference to the Series and return it return &SetAndSeries.series[seriesId] as &Series } pub fun createNewAdmin(): @Admin { return <-create Admin() } } //below is more from the SetAndSeries Contract ..... //the following code is used in init() at the end of the contract // Put Admin in storage self.account.save(<-create Admin(), to: self.AdminStoragePath) self.account.link<&SetAndSeries.Admin>( self.AdminPrivatePath, target: self.AdminStoragePath ) ?? panic("Could not get a capability to the admin")

An admin resource can be created and used as a way to only give access to certain key functions to specific accounts. In this instance our Admin resource contains the ability to create a series and the ability to borrow and return a Series resource.

Additionaly, this admin resource can create a new admin resource and give somebody else the ability to have access to this resource in their account.

At the end, when you are initializing your contract you are creating the Admin resource and saving it into the deployer of the smart contracts account. You would also create a private capability to the Admin account for a reference to all of the functions.

Transaction Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import SetAndSeries from 0x01 transaction { let adminCheck: &SetAndSeries.Admin prepare(acct: AuthAccount) { self.adminCheck = acct.borrow<&SetAndSeries.Admin>(from: SetAndSeries.AdminStoragePath) ?? panic("could not borrow admin reference") } execute { self.adminCheck.addSeries(seriesId: 1, metadata: {"Series": "1"}) log("series added") } }

Here we use the transaction to create a series from the admin account. We borrow a reference to the Admin resource and then use it to execute the addSeries function.


ProgressGetting Started With Access Management

Up Next: Add Admin Resource to Account

50%


Related Recipes

01 Apr 2022
Add Admin Resource to Account
Intermediate