Last active
January 20, 2023 16:36
-
-
Save sisyphusSmiling/418ca0bd9a734eb6750f40449c849140 to your computer and use it in GitHub Desktop.
Quick resource implementation defining a wrapped Provider Capability & withdrawal Limit, the wrapping resource itself implementing the FungibleToken.Provider standard.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import FungibleToken from 0xFUNGIBLETOKEN | |
/// Quick resource implementation defining a wrapped Provider Capability | |
/// with a withdrawal limit, the wrapping resource itself implementing | |
/// the FungibleToken.Provider standard. | |
/// | |
pub contract ScopedFungibleToken { | |
pub let ScopedProviderStoragePath: StoragePath | |
pub let ScopedProviderPrivatePath: PrivatePath | |
/// Resource wrapping a Provider Capability to enforce a withdrawal limit | |
pub resource ScopedProvider : FungibleToken.Provider { | |
/// Track how much has been withdrawn | |
pub var withdrawn: UFix64 | |
/// Set a limit on withdrawal | |
pub let withdrawalLimit: UFix64 | |
/// Maintain a Capability to the source Provider | |
pub let sourceProvider: Capability<&{FungibleToken.Provider}> | |
init( | |
_ withdrawalLimit: UFix64, | |
_ sourceProvider: Capability<&{FungibleToken.Provider}> | |
) { | |
pre { | |
sourceProvider.check(): "Problem with given Provider Capability!" | |
} | |
/* Assign resource variables on init */ | |
self.withdrawn = 0.0 | |
self.withdrawalLimit = withdrawalLimit | |
self.sourceProvider = sourceProvider | |
} | |
/// Provider.withdraw method implementation that enforces withdrawal limit | |
pub fun withdraw(amount: UFix64): @FungibleToken.Vault { | |
pre { | |
self.withdrawn + amount <= self.withdrawalLimit: "Amount exceeds remaining withdrawal limit!" | |
} | |
// Increment withdrawn amount before withdrawing | |
self.withdrawn = self.withdrawn + amount | |
// Get a reference to the Provider given on init | |
let sourceProviderRef = self.sourceProvider.borrow()! | |
// Return a Vault withdrawn from the source provider | |
return <-sourceProviderRef.withdraw(amount: amount) | |
} | |
} | |
/// Public method for anyone to create a ScopedProvider resource | |
pub fun createScopedProvider( | |
withdrawalLimit: UFix64, | |
sourceProvider: Capability<&{FungibleToken.Provider}> | |
): @ScopedProvider { | |
return <-create ScopedProvider(withdrawalLimit, sourceProvider) | |
} | |
init() { | |
self.ScopedProviderStoragePath = /storage/ScopedProvider | |
self.ScopedProviderPrivatePath = /private/ScopedProvider | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment