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

C1.0 migration #1

Merged
merged 10 commits into from
Dec 16, 2024
Merged
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
51 changes: 51 additions & 0 deletions .github/workflows/cadence_lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Run Cadence Contract Compilation, Deployment, Transaction Execution, and Lint
on: push

jobs:
run-cadence-lint:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: 'true'

- name: Install Flow CLI
run: |
brew update
brew install flow-cli

- name: Initialize Flow
run: |
if [ ! -f flow.json ]; then
echo "Initializing Flow project..."
flow init
else
echo "Flow project already initialized."
fi
flow dependencies install

- name: Start Flow Emulator
run: |
echo "Starting Flow emulator in the background..."
nohup flow emulator start > emulator.log 2>&1 &
sleep 5 # Wait for the emulator to start
flow project deploy --network=emulator # Deploy the recipe contracts indicated in flow.json

- name: Run All Transactions
run: |
echo "Running all transactions in the transactions folder..."
for file in ./cadence/transactions/*.cdc; do
echo "Running transaction: $file"
TRANSACTION_OUTPUT=$(flow transactions send "$file" --signer emulator-account)
echo "$TRANSACTION_OUTPUT"
if echo "$TRANSACTION_OUTPUT" | grep -q "Transaction Error"; then
echo "Transaction Error detected in $file, failing the action..."
exit 1
fi
done

- name: Run Cadence Lint
run: |
echo "Running Cadence linter on .cdc files in the current repository"
flow cadence lint ./cadence/**/*.cdc
34 changes: 34 additions & 0 deletions .github/workflows/cadence_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Run Cadence Tests
on: push

jobs:
run-cadence-tests:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: 'true'

- name: Install Flow CLI
run: |
brew update
brew install flow-cli

- name: Initialize Flow
run: |
if [ ! -f flow.json ]; then
echo "Initializing Flow project..."
flow init
else
echo "Flow project already initialized."
fi

- name: Run Cadence Tests
run: |
if test -f "cadence/tests.cdc"; then
echo "Running Cadence tests in the current repository"
flow test cadence/tests.cdc
else
echo "No Cadence tests found. Skipping tests."
fi
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.DS_Store
.DS_Store
/imports/
/.idea/
61 changes: 49 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This resource is used by the admin to mint more tokens.
- [Description](#description)
- [What is included in this repository?](#what-is-included-in-this-repository)
- [Supported Recipe Data](#recipe-data)
- [Deploying Recipe Contracts and Running Transactions Locally (Flow Emulator)](#deploying-recipe-contracts-and-running-transactions-locally-flow-emulator)
- [License](#license)

## Description
Expand All @@ -19,7 +20,6 @@ The Cadence Cookbook is a collection of code examples, recipes, and tutorials de

Each recipe in the Cadence Cookbook is a practical coding example that showcases a specific aspect of Cadence or use-case on Flow, including smart contract development, interaction, and best practices. By following these recipes, you can gain hands-on experience and learn how to leverage Cadence for your blockchain projects.


### Contributing to the Cadence Cookbook

Learn more about the contribution process [here](https://github.com/onflow/cadence-cookbook/blob/main/contribute.md).
Expand All @@ -34,17 +34,17 @@ Recipe metadata, such as title, author, and category labels, is stored in `index

```
recipe-name/
├── cadence/ # Cadence files for recipe examples
│ ├── contract.cdc # Contract code
│ ├── transaction.cdc # Transaction code
│ ├── tests.cdc # Tests code
├── explanations/ # Explanation files for recipe examples
│ ├── contract.txt # Contract code explanation
├── transaction.txt # Transaction code explanation
├── tests.txt # Tests code explanation
├── index.js # Root file for storing recipe metadata
├── README.md # This README file
└── LICENSE # License information
├── cadence/ # Cadence files for recipe examples
│ ├── contracts/Recipe.cdc # Contract code
│ ├── transactions/deposit_to_vault.cdc # Transaction code
│ ├── tests/Recipe_test.cdc # Tests code
├── explanations/ # Explanation files for recipe examples
│ ├── contract.txt # Contract code explanation
│ ├── transaction.txt # Transaction code explanation
│ ├── tests.txt # Tests code explanation
├── index.js # Root file for storing recipe metadata
├── README.md # This README file
└── LICENSE # License information
```

## Supported Recipe Data
Expand Down Expand Up @@ -95,6 +95,43 @@ export const sampleRecipe= {
transactionExplanation: transactionExplanationPath,
};
```
## Deploying Recipe Contracts and Running Transactions Locally (Flow Emulator)

This section explains how to deploy the recipe's contracts to the Flow emulator, run the associated transaction with sample arguments, and verify the results.

### Prerequisites

Before deploying and running the recipe:

1. Install the Flow CLI. You can find installation instructions [here](https://docs.onflow.org/flow-cli/install/).
2. Ensure the Flow emulator is installed and ready to use with `flow version`.

### Step 1: Start the Flow Emulator

Start the Flow emulator to simulate the blockchain environment locally

```bash
flow emulator start
```

### Step 2: Install Dependencies and Deploy Project Contracts

Deploy contracts to the emulator. This will deploy all the contracts specified in the _deployments_ section of `flow.json` whether project contracts or dependencies.

```bash
flow dependencies install
flow project deploy --network=emulator
```

### Step 3: Run the Transaction

Transactions associated with the recipe are located in `./cadence/transactions`. To run a transaction, execute the following command:

```bash
flow transactions send cadence/transactions/TRANSACTION_NAME.cdc --signer emulator-account
```

To verify the transaction's execution, check the emulator logs printed during the transaction for confirmation messages. You can add the `--log-level debug` flag to your Flow CLI command for more detailed output during contract deployment or transaction execution.

## License

Expand Down
17 changes: 0 additions & 17 deletions cadence/contract.cdc

This file was deleted.

1 change: 1 addition & 0 deletions cadence/contract.cdc
187 changes: 187 additions & 0 deletions cadence/contracts/Recipe.cdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/// ExampleToken.cdc
///
/// The ExampleToken contract is a sample implementation of a fungible token on Flow.
///
/// Fungible tokens behave like everyday currencies -- they can be minted, transferred or
/// traded for digital goods.
///
/// This is a basic implementation of a Fungible Token and is NOT meant to be used in production
/// See the Flow Fungible Token standard for real examples: https://github.com/onflow/flow-ft

access(all) contract ExampleToken {

access(all) entitlement Withdraw

access(all) let VaultStoragePath: StoragePath
access(all) let VaultPublicPath: PublicPath

access(all) var totalSupply: UFix64

/// Balance
///
/// The interface that provides a standard field
/// for representing balance
///
access(all) resource interface Balance {
access(all) var balance: UFix64
}

/// Provider
///
/// The interface that enforces the requirements for withdrawing
/// tokens from the implementing type.
///
/// It does not enforce requirements on `balance` here,
/// because it leaves open the possibility of creating custom providers
/// that do not necessarily need their own balance.
///
access(all) resource interface Provider {

/// withdraw subtracts tokens from the implementing resource
/// and returns a Vault with the removed tokens.
///
/// The function's access level is `access(Withdraw)`
/// 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
result.balance == amount:
"ExampleToken.Provider.withdraw: Cannot withdraw tokens!"
.concat("The balance of the withdrawn tokens (").concat(result.balance.toString())
.concat(") is not equal to the amount requested to be withdrawn (")
.concat(amount.toString()).concat(")")
}
}
}

/// Receiver
///
/// The interface that enforces the requirements for depositing
/// tokens into the implementing type.
///
/// We do not include a condition that checks the balance because
/// we want to give users the ability to make custom receivers that
/// can do custom things with the tokens, like split them up and
/// send them to different places.
///
access(all) resource interface Receiver {

/// 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)
}

/// Vault
///
/// Each user stores an instance of only the Vault in their storage
/// The functions in the Vault are governed by the pre and post conditions
/// in the interfaces 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 or constructor function needs to be defined to mint
/// new tokens.
///
access(all) resource Vault: Balance, Provider, Receiver {

/// keeps track of the total balance of the account's tokens
access(all) var balance: UFix64

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

/// withdraw
///
/// Function that takes an integer amount as an argument
/// and withdraws that amount from the Vault.
///
/// It creates a new temporary Vault that is used to hold
/// the money that is being transferred. It returns the newly
/// created Vault to the context that called so it can be deposited
/// elsewhere.
///
access(Withdraw) fun withdraw(amount: UFix64): @Vault {
pre {
self.balance >= amount:
"ExampleToken.Vault.withdraw: Cannot withdraw tokens! "
.concat("The amount requested to be withdrawn (").concat(amount.toString())
.concat(") is greater than the balance of the Vault (")
.concat(self.balance.toString()).concat(").")
}
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: @Vault) {
self.balance = self.balance + from.balance
destroy from
}
}

/// createEmptyVault
///
access(all) fun createEmptyVault(): @Vault {
return <-create Vault(balance: 0.0)
}

// VaultMinter
//
// Resource object that an admin can control to mint new tokens
access(all) resource VaultMinter {

// Function that mints new tokens and deposits into an account's vault
// using their `{Receiver}` reference.
// We say `&{Receiver}` to say that the recipient can be any resource
// as long as it implements the Receiver interface
access(all) fun mintTokens(amount: UFix64, recipient: Capability<&{Receiver}>) {
let recipientRef = recipient.borrow()
?? panic("ExampleToken.VaultMinter.mintTokens: Could not borrow a receiver reference to "
.concat("the specified recipient's ExampleToken.Vault")
.concat(". Make sure the account has set up its account ")
.concat("with an ExampleToken Vault and valid capability."))

ExampleToken.totalSupply = ExampleToken.totalSupply + UFix64(amount)
recipientRef.deposit(from: <-create Vault(balance: amount))
}
}

/// The init function for the contract. All fields in the contract must
/// be initialized at deployment. This is just an example of what
/// an implementation could do in the init function. The numbers are arbitrary.
init() {
self.VaultStoragePath = /storage/CadenceFungibleTokenTutorialVault
self.VaultPublicPath = /public/CadenceFungibleTokenTutorialReceiver

self.totalSupply = 30.0

// create the Vault with the initial balance and put it in storage
// account.save saves an object to the specified `to` path
// The path is a literal path that consists of a domain and identifier
// The domain must be `storage`, `private`, or `public`
// the identifier can be any name
let vault <- create Vault(balance: self.totalSupply)
self.account.storage.save(<-vault, to: self.VaultStoragePath)

// Create a new VaultMinter resource and store it in account storage
self.account.storage.save(<-create VaultMinter(), to: /storage/CadenceFungibleTokenTutorialMinter)

}
}
Loading