Learn everything about Aptos
Smart Contract Demonstration Part-2
Aptos Smart Contract Tutorial – Claim and Withdraw Token Functions
In this video, we’ll continue building our Aptos smart contract by implementing two essential entry functions: claim tokens and withdraw tokens.
1. Claim Tokens Function
This function allows users to claim their allocated tokens from the Vault.
Function Declaration
public entry fun claim_tokens(account: &signer, admin_address: address)
acquires Vault, VaultSignerCapability
Key Steps:
- Check Allocation: Verify that the account address exists in the Vault’s allocation table. If not, return a NoAllocation error.
- Remove Allocation: Remove the allocation from the table. The remove method returns the allocated amount.
- Validate Balance: Ensure the Vault’s total balance is greater than or equal to the claimed amount. If not, return InsufficientBalance.
- Update Vault Records:
- Decrease total_allocated by the claimed amount.
- Decrease total_balance accordingly.
- Create Vault Signer:
- Retrieve signer capability from the admin address.
- Use this to create a signer for the Vault.
- Ensure Account Registration:
- Check if the recipient account is registered to receive Aptos coins.
- If not, register it.
- Transfer Tokens:
- Transfer the claimed tokens using the Vault signer.
- Emit Event:
- Emit AllocationClaimedEvent with the account address and amount.
2. Withdraw Tokens Function
This function enables the admin to withdraw unallocated tokens from the Vault.
Function Declaration
public entry fun withdraw_tokens(admin: &signer, amount: u64)
acquires Vault, VaultSignerCapability
Key Steps:
- Admin Verification:
- Retrieve the Vault and check if the signer matches the stored admin address.
- If not, return NotAdmin.
- Calculate Available Balance:
- available_balance = total_balance - total_allocated
- Only this amount is withdrawable by the admin.
- Check Withdrawable Amount:
- Ensure the requested amount does not exceed the available_balance.
- If it does, return InsufficientBalance.
- Create Vault Signer:
- Use the signer capability from the admin to create the Vault signer.
- Transfer Tokens:
- Transfer the specified amount from the Vault to the admin’s address.
- Emit Event:
- Emit a WithdrawEvent recording the withdrawal.
Summary
In both functions, the process follows a clear pattern:
- Retrieve the Vault.
- Validate permissions and conditions.
- Update Vault state (balances and allocations).
- Transfer coins using the Vault signer.
- Emit relevant events.
This structure ensures consistency and security in handling token transfers.
Comments
You need to enroll in the course to be able to comment!