To learn more about implementing an official NFT contract in Cadence, check out Emerald Academy’s Beginner Cadence course which does exactly that.
造币功能
现在我们已经涵盖了实施NFT标准,让我们加入合同的其余部分。
下一个最重要的步骤是重写造币。这就是Solidity合约中的造币功能:
function mintApe(uint numberOfTokens) publicpayable {
require(saleIsActive, "Sale must be active to mint Ape");
require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes");
require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_APES) {
_safeMint(msg.sender, mintIndex);
}
}
}
铸币功能的第一步是确保一些检查是真的:
检查以确保销售是活跃的
不允许用户铸造超过允许的最大数额的硬币
确保总供应量不会超过允许的最大猿数
确保传递进来的以太数量等于被购买的猿猴的(价格*数量)。
然后,它运行一个循环,用发件人的地址和一个代表每个NFT的增量id调用mint函数。
为了在Cadence中实现这一点,我们需要定义一些变量来运行我们的检查,然后定义一个薄荷函数:
// custom variablespublet apePrice: UFix64
publet maxApePurchase: UInt64
pubvar maxApes: UInt64
pubvar saleIsActive: Bool
pubfun mintApe(
numberOfTokens: UInt64,
payment: @FlowToken.Vault,
recipientVault: &Collection{NonFungibleToken.Receiver}
) {
pre {
BoredApeYachtClub.saleIsActive: "Sale must be active to mint Ape"
numberOfTokens <= BoredApeYachtClub.maxApePurchase: "Can only mint 20 tokens at a time"
BoredApeYachtClub.totalSupply + numberOfTokens <= BoredApeYachtClub.maxApes: "Purchase would exceed max supply of Apes"
BoredApeYachtClub.apePrice * UFix64(numberOfTokens) == payment.balance: "$FLOW value sent is not correct"
}
var i: UInt64 = 0
while i < numberOfTokens {
recipientVault.deposit(token: <- create NFT())
i = i + 1
}
// deposit the payment to the contract ownerlet ownerVault = BoredApeYachtClub.account.getCapability(/public/flowTokenReceiver)
.borrow<&FlowToken.Vault{FungibleToken.Receiver}>()
?? panic("Could not get the Flow Token Vault from the Owner of this contract.")
ownerVault.deposit(from: <- payment)
}
init(maxNftSupply: UInt64) {
self.apePrice = 0.08 // $FLOW
self.maxApePurchase = 20
self.maxApes = maxNftSupply
self.saleIsActive = false
}