Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add assertions to generic transfer and update docs #166

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ There is no need to deploy them yourself.
| ----------------- | -------------------- |
| Emulator | `0xee82856bf20e2aa6` |
| PreviewNet | `0xa0225e7000ac82a9` |
| Testnet/Crescendo | `0x9a0766d93b6608b7` |
| Testnet | `0x9a0766d93b6608b7` |
| Sandboxnet | `0xe20612a0776ca4bf` |
| Mainnet | `0xf233dcee88fe0abe` |

Expand Down
3 changes: 2 additions & 1 deletion contracts/ExampleToken.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ access(all) contract ExampleToken: FungibleToken {
self.balance = 0.0
}

/// In fungible tokens, there are no specific views for specific vaults,
/// So we can route calls to view functions to the contract views functions
access(all) view fun getViews(): [Type] {
return ExampleToken.getContractViews(resourceType: nil)
}
Expand Down Expand Up @@ -150,7 +152,6 @@ access(all) contract ExampleToken: FungibleToken {
access(all) fun deposit(from: @{FungibleToken.Vault}) {
let vault <- from as! @ExampleToken.Vault
self.balance = self.balance + vault.balance
vault.balance = 0.0
destroy vault
}

Expand Down
63 changes: 45 additions & 18 deletions contracts/FungibleToken.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ Each fungible token resource type needs to implement the `Vault` resource interf
These interfaces declare pre-conditions and post-conditions that restrict
the execution of the functions in the Vault.

They are separate because it gives the user the ability to share
a reference to their Vault that only exposes the fields functions
in one or more of the interfaces.

It also gives users the ability to make custom resources that implement
It gives users the ability to make custom resources that implement
these interfaces to do various things with the tokens.
For example, a faucet can be implemented by conforming
to the Provider interface.
Expand All @@ -52,19 +48,32 @@ access(all) contract interface FungibleToken: ViewResolver {
// An entitlement for allowing the withdrawal of tokens from a Vault
access(all) entitlement Withdraw

/// The event that is emitted when tokens are withdrawn from a Vault
access(all) event Withdrawn(type: String, amount: UFix64, from: Address?, fromUUID: UInt64, withdrawnUUID: UInt64, balanceAfter: UFix64)

/// The event that is emitted when tokens are deposited to a Vault
access(all) event Deposited(type: String, amount: UFix64, to: Address?, toUUID: UInt64, depositedUUID: UInt64, balanceAfter: UFix64)

/// Event that is emitted when the global burn method is called with a non-zero balance
/// The event that is emitted when tokens are withdrawn
/// from any Vault that implements the `Vault` interface
access(all) event Withdrawn(type: String,
amount: UFix64,
from: Address?,
fromUUID: UInt64,
withdrawnUUID: UInt64,
balanceAfter: UFix64)

/// The event that is emitted when tokens are deposited to
/// any Vault that implements the `Vault` interface
access(all) event Deposited(type: String,
amount: UFix64,
to: Address?,
toUUID: UInt64,
depositedUUID: UInt64,
balanceAfter: UFix64)

/// Event that is emitted when the global `Burner.burn()` method
/// is called with a non-zero balance
access(all) event Burned(type: String, amount: UFix64, fromUUID: UInt64)

/// Balance
///
/// The interface that provides standard functions\
/// for getting balance information
/// The interface that provides a standard field
/// for representing balance
///
access(all) resource interface Balance {
access(all) var balance: UFix64
Expand All @@ -88,6 +97,9 @@ access(all) contract interface FungibleToken: ViewResolver {
/// Additionally, if the provider is pulling from multiple vaults
/// it only needs to check some of the vaults until the desired amount
/// is reached, potentially helping with performance.
///
/// @param amount the amount of tokens requested to potentially withdraw
/// @return Bool Whether or not this amount is available to withdraw
///
access(all) view fun isAvailableToWithdraw(amount: UFix64): Bool

Expand All @@ -98,6 +110,9 @@ access(all) contract interface FungibleToken: ViewResolver {
/// So in order to access it, one would either need the object itself
/// or an entitled reference with `Withdraw`.
///
/// @param amount the amount of tokens to withdraw from the resource
/// @return The Vault with the withdrawn tokens
///
access(Withdraw) fun withdraw(amount: UFix64): @{Vault} {
post {
// `result` refers to the return value
Expand All @@ -121,21 +136,30 @@ access(all) contract interface FungibleToken: ViewResolver {

/// deposit takes a Vault and deposits it into the implementing resource type
///
/// @param from the Vault that contains the tokens to deposit
///
access(all) fun deposit(from: @{Vault})

/// getSupportedVaultTypes returns a dictionary of Vault types
/// and whether the type is currently supported by this Receiver
///
/// @return {Type: Bool} A dictionary that indicates the supported types
/// If a type is not supported, it should be `nil`, not false
///
access(all) view fun getSupportedVaultTypes(): {Type: Bool}

/// Returns whether or not the given type is accepted by the Receiver
/// A vault that can accept any type should just return true by default
///
/// @param type The type to query about
/// @return Bool Whether or not the vault type is supported
///
access(all) view fun isSupportedVaultType(type: Type): Bool
}

/// Vault
///
/// Ideally, this interface would also conform to Receiver, Balance, Transferor, Provider, and Resolver
/// but that is not supported yet
/// Conforms to all other interfaces so that implementations
/// only have to conform to `Vault`
///
access(all) resource interface Vault: Receiver, Provider, Balance, ViewResolver.Resolver, Burner.Burnable {

Expand All @@ -159,10 +183,11 @@ access(all) contract interface FungibleToken: ViewResolver {
self.balance = 0.0
}

/// getSupportedVaultTypes returns a dictionary of vault types and whether this receiver accepts the indexed type
/// getSupportedVaultTypes
/// The default implementation is included here because vaults are expected
/// to only accepted their own type, so they have no need to provide an implementation
/// for this function
///
access(all) view fun getSupportedVaultTypes(): {Type: Bool} {
// Below check is implemented to make sure that run-time type would
// only get returned when the parent resource conforms with `FungibleToken.Vault`.
Expand Down Expand Up @@ -231,6 +256,7 @@ access(all) contract interface FungibleToken: ViewResolver {

/// createEmptyVault allows any user to create a new Vault that has a zero balance
///
/// @return A Vault of the same type that has a balance of zero
access(all) fun createEmptyVault(): @{Vault} {
post {
result.balance == 0.0: "The newly created Vault must have zero balance"
Expand All @@ -241,6 +267,7 @@ access(all) contract interface FungibleToken: ViewResolver {

/// createEmptyVault allows any user to create a new Vault that has a zero balance
///
/// @return A Vault of the requested type that has a balance of zero
access(all) fun createEmptyVault(vaultType: Type): @{FungibleToken.Vault} {
post {
result.getType() == vaultType: "The returned vault does not match the desired type"
Expand Down
212 changes: 212 additions & 0 deletions contracts/test/MaliciousToken.cdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import "FungibleToken"
import "MetadataViews"
import "FungibleTokenMetadataViews"
import "ExampleToken"

/// This is a contract that returns metadata for a different token
/// type to try to get a user who is transferring tokens
/// via the generic transactions to transfer the wrong tokens

access(all) contract MaliciousToken: FungibleToken {

/// The event that is emitted when new tokens are minted
access(all) event TokensMinted(amount: UFix64, type: String)

/// Total supply of MaliciousTokens in existence
access(all) var totalSupply: UFix64

/// Storage and Public Paths
access(all) let VaultStoragePath: StoragePath
access(all) let VaultPublicPath: PublicPath
access(all) let ReceiverPublicPath: PublicPath
access(all) let AdminStoragePath: StoragePath

access(all) view fun getContractViews(resourceType: Type?): [Type] {
return [
Type<FungibleTokenMetadataViews.FTView>(),
Type<FungibleTokenMetadataViews.FTVaultData>(),
Type<FungibleTokenMetadataViews.TotalSupply>()
]
}

access(all) fun resolveContractView(resourceType: Type?, viewType: Type): AnyStruct? {
switch viewType {
case Type<FungibleTokenMetadataViews.FTView>():
return FungibleTokenMetadataViews.FTView(
ftDisplay: self.resolveContractView(resourceType: nil, viewType: Type<FungibleTokenMetadataViews.FTDisplay>()) as! FungibleTokenMetadataViews.FTDisplay?,
ftVaultData: self.resolveContractView(resourceType: nil, viewType: Type<FungibleTokenMetadataViews.FTVaultData>()) as! FungibleTokenMetadataViews.FTVaultData?
)
case Type<FungibleTokenMetadataViews.FTVaultData>():
return FungibleTokenMetadataViews.FTVaultData(
storagePath: /storage/exampleTokenVault,
receiverPath: /public/exampleTokenReceiver,
metadataPath: /public/exampleTokenVault,
receiverLinkedType: Type<&ExampleToken.Vault>(),
metadataLinkedType: Type<&ExampleToken.Vault>(),
createEmptyVaultFunction: (fun(): @{FungibleToken.Vault} {
return <-MaliciousToken.createEmptyVault(vaultType: Type<@MaliciousToken.Vault>())
})
)
case Type<FungibleTokenMetadataViews.TotalSupply>():
return FungibleTokenMetadataViews.TotalSupply(
totalSupply: MaliciousToken.totalSupply
)
}
return nil
}

/// Vault
///
/// Each user stores an instance of only the Vault in their storage
/// The functions in the Vault and governed by the pre and post conditions
/// in FungibleToken when they are called.
/// The checks happen at runtime whenever a function is called.
///
/// Resources can only be created in the context of the contract that they
/// are defined in, so there is no way for a malicious user to create Vaults
/// out of thin air. A special Minter resource needs to be defined to mint
/// new tokens.
///
access(all) resource Vault: FungibleToken.Vault {

/// The total balance of this vault
access(all) var balance: UFix64

// initialize the balance at resource creation time
init(balance: UFix64) {
self.balance = balance
}

/// Called when a fungible token is burned via the `Burner.burn()` method
access(contract) fun burnCallback() {
if self.balance > 0.0 {
MaliciousToken.totalSupply = MaliciousToken.totalSupply - self.balance
}
self.balance = 0.0
}

/// In fungible tokens, there are no specific views for specific vaults,
/// So we can route calls to view functions to the contract views functions
access(all) view fun getViews(): [Type] {
return MaliciousToken.getContractViews(resourceType: nil)
}

access(all) fun resolveView(_ view: Type): AnyStruct? {
return MaliciousToken.resolveContractView(resourceType: nil, viewType: view)
}

/// getSupportedVaultTypes optionally returns a list of vault types that this receiver accepts
access(all) view fun getSupportedVaultTypes(): {Type: Bool} {
let supportedTypes: {Type: Bool} = {}
supportedTypes[self.getType()] = true
return supportedTypes
}

access(all) view fun isSupportedVaultType(type: Type): Bool {
return self.getSupportedVaultTypes()[type] ?? false
}

/// Asks if the amount can be withdrawn from this vault
access(all) view fun isAvailableToWithdraw(amount: UFix64): Bool {
return amount <= self.balance
}

/// withdraw
///
/// Function that takes an amount as an argument
/// and withdraws that amount from the Vault.
///
/// It creates a new temporary Vault that is used to hold
/// the tokens that are being transferred. It returns the newly
/// created Vault to the context that called so it can be deposited
/// elsewhere.
///
access(FungibleToken.Withdraw) fun withdraw(amount: UFix64): @MaliciousToken.Vault {
self.balance = self.balance - amount
return <-create Vault(balance: amount)
}

/// deposit
///
/// Function that takes a Vault object as an argument and adds
/// its balance to the balance of the owners Vault.
///
/// It is allowed to destroy the sent Vault because the Vault
/// was a temporary holder of the tokens. The Vault's balance has
/// been consumed and therefore can be destroyed.
///
access(all) fun deposit(from: @{FungibleToken.Vault}) {
let vault <- from as! @MaliciousToken.Vault
self.balance = self.balance + vault.balance
destroy vault
}

/// createEmptyVault
///
/// Function that creates a new Vault with a balance of zero
/// and returns it to the calling context. A user must call this function
/// and store the returned Vault in their storage in order to allow their
/// account to be able to receive deposits of this token type.
///
access(all) fun createEmptyVault(): @MaliciousToken.Vault {
return <-create Vault(balance: 0.0)
}
}

/// Minter
///
/// Resource object that token admin accounts can hold to mint new tokens.
///
access(all) resource Minter {
/// mintTokens
///
/// Function that mints new tokens, adds them to the total supply,
/// and returns them to the calling context.
///
access(all) fun mintTokens(amount: UFix64): @MaliciousToken.Vault {
MaliciousToken.totalSupply = MaliciousToken.totalSupply + amount
let vault <-create Vault(balance: amount)
emit TokensMinted(amount: amount, type: vault.getType().identifier)
return <-vault
}
}

/// createEmptyVault
///
/// Function that creates a new Vault with a balance of zero
/// and returns it to the calling context. A user must call this function
/// and store the returned Vault in their storage in order to allow their
/// account to be able to receive deposits of this token type.
///
access(all) fun createEmptyVault(vaultType: Type): @MaliciousToken.Vault {
return <- create Vault(balance: 0.0)
}

init() {
self.totalSupply = 1000.0

self.VaultStoragePath = /storage/maliciousTokenVault
self.VaultPublicPath = /public/maliciousTokenVault
self.ReceiverPublicPath = /public/maliciousTokenReceiver
self.AdminStoragePath = /storage/maliciousTokenAdmin

// Create the Vault with the total supply of tokens and save it in storage
//
let vault <- create Vault(balance: self.totalSupply)
emit TokensMinted(amount: vault.balance, type: vault.getType().identifier)

// Create a public capability to the stored Vault that exposes
// the `deposit` method and getAcceptedTypes method through the `Receiver` interface
// and the `balance` method through the `Balance` interface
//
let maliciousTokenCap = self.account.capabilities.storage.issue<&MaliciousToken.Vault>(self.VaultStoragePath)
self.account.capabilities.publish(maliciousTokenCap, at: self.VaultPublicPath)
let receiverCap = self.account.capabilities.storage.issue<&MaliciousToken.Vault>(self.VaultStoragePath)
self.account.capabilities.publish(receiverCap, at: self.ReceiverPublicPath)

self.account.storage.save(<-vault, to: /storage/maliciousTokenVault)

let admin <- create Minter()
self.account.storage.save(<-admin, to: self.AdminStoragePath)
}
}
Loading
Loading