All files / token BasicTokenContract.ts

100% Statements 46/46
100% Branches 0/0
100% Functions 11/11
100% Lines 45/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374                                                                                                                                                                                                                                                                  91x                               8x   8x   8x                                             4x       12x 12x 12x 12x 12x                         8x 8x 8x     4x 12x                                   4x         18x 18x     18x   18x             18x         18x                                   4x 12x 12x     12x   12x       12x                                   4x         15x 15x   15x   15x             15x         15x                                           4x 12x 12x   12x   12x         12x                           4x         12x               4x   4x    
import {
  SmartContract,
  state,
  State,
  method,
  Permissions,
  UInt64,
  PublicKey,
  Signature,
  AccountUpdate,
  VerificationKey,
  TokenContract,
  AccountUpdateForest,
} from 'o1js';
 
/**
 * Defines the basic interface for a token contract.
 *
 * All token contracts should inherit from this class and implement its methods.
 *
 * @remarks
 * This class is designed to provide a standardized way of interacting with token contracts,
 * ensuring consistency and interoperability across different implementations.
 */
export abstract class IBasicTokenContract {
  /**
   * Deploys the token contract to the blockchain.
   *
   * @remarks
   * This method should handle all necessary steps for deploying the contract,
   * such as configuring ownership.
   */
  abstract deploy(): Promise<void>;
 
  /**
   * Initializes the token contract after deployment.
   *
   * @remarks
   * This method is used to perform any additional setup tasks after the contract is deployed,
   * such as setting initial token balances or defining access control rules.
   */
  abstract init(): void;
 
  /**
   * Mints new tokens with signature and assigns them to a receiver.
   *
   * @param receiverAddress - The address of the receiver who will receive the newly minted tokens
   * @param amount - The amount of tokens to mint
   * @param adminSignature - A signature from an authorized administrator, required to approve the minting
   */
  abstract mintWithSignature(
    receiverAddress: PublicKey,
    amount: UInt64,
    adminSignature: Signature
  ): Promise<void>;
 
  /**
   * Mints new tokens and assigns them to a receiver. (require signature)
   *
   * @param receiverAddress - The address of the receiver who will receive the newly minted tokens
   * @param amount - The amount of tokens to mint
   */
  abstract mint(receiverAddress: PublicKey, amount: UInt64): Promise<void>;
 
  /**
   * Burning (destroying) tokens with signature, reducing the total supply.
   *
   * @param receiverAddress - The address of the token holder whose tokens will be burned
   * @param amount - The amount of tokens to burn
   * @param adminSignature - A signature from an authorized administrator, required to approve the burning
   */
  abstract burnWithSignature(
    receiverAddress: PublicKey,
    amount: UInt64,
    adminSignature: Signature
  ): Promise<void>;
 
  /**
   * Burning (destroying) tokens, reducing the total supply. (require signature)
   *
   * @param receiverAddress - The address of the token holder whose tokens will be burned
   * @param amount - The amount of tokens to burn
   */
  abstract burn(receiverAddress: PublicKey, amount: UInt64): Promise<void>;
 
  /**
   * Sends tokens from one address to another.
   *
   * @param senderAddress - The address of the sender who is transferring the tokens
   * @param receiverAddress - The address of the receiver who will receive the tokens
   * @param amount - The amount of tokens to transfer
   */
  abstract sendTokens(
    senderAddress: PublicKey,
    receiverAddress: PublicKey,
    amount: UInt64
  ): Promise<void>;
}
 
/**
 * Creates a basic token contract instance.
 *
 * @param address - The address where the contract will be deployed
 * @param symbol - The symbol for the token (e.g., "MYTOKEN")
 * @returns A promise that resolves to the created token contract instance
 *
 * @remarks
 * This function handles the following steps:
 * 1. Compiles the `BasicTokenContract` class.
 * 2. Initializes the contract with the provided symbol.
 * 3. Sets up necessary permissions for the contract.
 * 4. Returns the newly created contract instance.
 */
export async function buildBasicTokenContract(
  address: PublicKey,
  symbol: string
): Promise<TokenContract & IBasicTokenContract> {
  class BasicTokenContract
    extends TokenContract
    implements IBasicTokenContract
  {
    /**
     * Stores the total amount of tokens in circulation.
     *
     * @type {State<UInt64>}
     * @remarks
     * This state variable is crucial for tracking the supply of tokens within the contract.
     * It's updated during minting and potentially other token-related operations to ensure accurate accounting.
     */
    @state(UInt64) totalAmountInCirculation = State<UInt64>();
 
    /**
     * Deploys the contract to the blockchain and configures permissions.
     *
     * @remarks
     * This method performs the following steps:
     * 1. Calls the superclass's `deploy` method to handle initial deployment tasks.
     * 2. Creates a proof-based permission that requires a valid signature for authorization.
     * 3. Sets the contract's permissions to restrict actions:
     *   - `editState`: Requires proof to modify contract state.
     *   - `setTokenSymbol`: Requires proof to change the token symbol.
     *   - `send`: Requires proof to send tokens from the contract.
     *   - `receive`: Requires proof to receive tokens into the contract.
     */
    public async deploy() {
      await super.deploy();
 
      const permissionToEdit = Permissions.proof();
 
      this.account.permissions.set({
        ...Permissions.default(),
        editState: permissionToEdit,
        setTokenSymbol: permissionToEdit,
        send: permissionToEdit,
        receive: permissionToEdit,
      });
    }
 
    /**
     * Deploys a zkApp (zero-knowledge application) account with standard permissions.
     *
     * @remarks
     * This method performs the following steps:
     * 1. Retrieves the token ID associated with the contract.
     * 2. Creates a default account update instruction for the zkApp's address and token ID.
     * 3. Approves the account update, authorizing the creation of the zkApp account.
     * 4. Sets default permissions for the zkApp account.
     * 5. Stores the provided verification key in the zkApp account's state.
     *
     * @param address - The address where the zkApp account will be deployed
     * @param verificationKey - The verification key to be associated with the zkApp account
     */
    @method async deployZkapp(
      address: PublicKey,
      verificationKey: VerificationKey
    ) {
      let tokenId = this.deriveTokenId();
      let zkapp = AccountUpdate.defaultAccountUpdate(address, tokenId);
      this.approve(zkapp);
      zkapp.account.permissions.set(Permissions.default());
      zkapp.account.verificationKey.set(verificationKey);
    }
 
    /**
     * Initializes the contract after deployment.
     *
     * @remarks
     * This method performs the following steps:
     * 1. Calls the superclass's `init` method to handle any base initialization tasks.
     * 2. Sets the token symbol for the contract.
     * 3. Initializes the total amount of tokens in circulation to zero.
     */
    init() {
      super.init();
      this.account.tokenSymbol.set(symbol);
      this.totalAmountInCirculation.set(UInt64.zero);
    }
 
    @method async approveBase(forest: AccountUpdateForest) {
      this.checkZeroBalanceChange(forest);
    }
 
    /**
     * Mints new tokens with signature and assigns them to a receiver.
     *
     * @remarks
     * This function performs the following steps:
     * 1. Retrieves the current total supply of tokens in circulation.
     * 2. Asserts consistency of the retrieved state value.
     * 3. Verifies that the minting process is authorized by an administrator.
     * 4. Calls the underlying token module to mint the new tokens.
     * 5. Updates the total token supply in the contract's state.
     *
     * @param receiverAddress - The address of the receiver who will receive the newly minted tokens
     * @param amount - The amount of tokens to mint
     * @param adminSignature - A signature from an authorized administrator, required to approve the minting
     */
    @method async mintWithSignature(
      receiverAddress: PublicKey,
      amount: UInt64,
      adminSignature: Signature
    ) {
      let totalAmountInCirculation = this.totalAmountInCirculation.get();
      this.totalAmountInCirculation.requireEquals(totalAmountInCirculation);
      // this.totalAmountInCirculation.assertEquals(totalAmountInCirculation);
 
      let newTotalAmountInCirculation = totalAmountInCirculation.add(amount);
 
      adminSignature
        .verify(
          this.address,
          amount.toFields().concat(receiverAddress.toFields())
        )
        .assertTrue();
 
      this.internal.mint({
        address: receiverAddress,
        amount,
      });
 
      this.totalAmountInCirculation.set(newTotalAmountInCirculation);
    }
 
    /**
     * Mints new tokens and assigns them to a receiver.
     *
     * @remarks
     * This method assumes that authorization checks for minting are handled elsewhere.
     * It directly performs the following steps:
     * 1. Retrieves the current total supply of tokens in circulation.
     * 2. Asserts consistency of the retrieved state value.
     * 3. Calculates the new total supply after minting.
     * 4. Calls the underlying token module to mint the new tokens.
     * 5. Updates the total token supply in the contract's state.
     *
     * @param receiverAddress - The address of the receiver who will receive the newly minted tokens
     * @param amount - The amount of tokens to mint
     */
    @method async mint(receiverAddress: PublicKey, amount: UInt64) {
      let totalAmountInCirculation = this.totalAmountInCirculation.get();
      this.totalAmountInCirculation.requireEquals(totalAmountInCirculation);
      // this.totalAmountInCirculation.assertEquals(totalAmountInCirculation);
 
      let newTotalAmountInCirculation = totalAmountInCirculation.add(amount);
 
      this.internal.mint({
        address: receiverAddress,
        amount,
      });
      this.totalAmountInCirculation.set(newTotalAmountInCirculation);
    }
 
    /**
     * Burns (destroys) existing tokens with signature, reducing the total supply.
     *
     * @remarks
     * This method performs the following steps:
     * 1. Retrieves the current total supply of tokens in circulation.
     * 2. Asserts consistency of the retrieved state value.
     * 3. Verifies that the burning process is authorized by an administrator.
     * 4. Calls the underlying token module to burn the specified amount of tokens.
     * 5. Updates the total token supply in the contract's state to reflect the reduction.
     *
     * @param receiverAddress - The address of the token holder whose tokens will be burned
     * @param amount - The amount of tokens to burn
     * @param adminSignature - A signature from an authorized administrator, required to approve the burning
     */
    @method async burnWithSignature(
      receiverAddress: PublicKey,
      amount: UInt64,
      adminSignature: Signature
    ) {
      let totalAmountInCirculation = this.totalAmountInCirculation.get();
      this.totalAmountInCirculation.requireEquals(totalAmountInCirculation);
      // this.totalAmountInCirculation.assertEquals(totalAmountInCirculation);
      let newTotalAmountInCirculation = totalAmountInCirculation.sub(amount);
 
      adminSignature
        .verify(
          this.address,
          amount.toFields().concat(receiverAddress.toFields())
        )
        .assertTrue();
 
      this.internal.burn({
        address: receiverAddress,
        amount,
      });
 
      this.totalAmountInCirculation.set(newTotalAmountInCirculation);
    }
 
    /**
     * Burns (destroys) existing tokens, reducing the total supply.
     *
     * @remarks
     * This method assumes that authorization checks for burning are handled elsewhere.
     * It directly performs the following steps:
     * 1. Retrieves the current total supply of tokens in circulation.
     * 2. Asserts consistency of the retrieved state value.
     * 3. Calculates the new total supply after burning.
     * 4. Calls the underlying token module to burn the specified tokens.
     * 5. Updates the total token supply in the contract's state.
     *
     * @param receiverAddress - The address of the token holder whose tokens will be burned
     * @param amount - The amount of tokens to burn
     *
     * @warning This method does not explicitly check for authorization to burn tokens.
     *          It's essential to ensure that appropriate authorization mechanisms are in place
     *          to prevent unauthorized token burning.
     */
    @method async burn(receiverAddress: PublicKey, amount: UInt64) {
      let totalAmountInCirculation = this.totalAmountInCirculation.get();
      this.totalAmountInCirculation.requireEquals(totalAmountInCirculation);
      // this.totalAmountInCirculation.assertEquals(totalAmountInCirculation);
      let newTotalAmountInCirculation = totalAmountInCirculation.sub(amount);
 
      this.internal.burn({
        address: receiverAddress,
        amount,
      });
 
      this.totalAmountInCirculation.set(newTotalAmountInCirculation);
    }
 
    /**
     * Sends tokens from one address to another.
     *
     * @remarks
     * This function delegates the transfer of tokens to the underlying token module.
     * It does not directly handle token accounting or permissions within this contract.
     *
     * @param senderAddress - The address of the sender who is transferring the tokens
     * @param receiverAddress - The address of the receiver who will receive the tokens
     * @param amount - The amount of tokens to transfer
     */
    @method async sendTokens(
      senderAddress: PublicKey,
      receiverAddress: PublicKey,
      amount: UInt64
    ) {
      this.internal.send({
        from: senderAddress,
        to: receiverAddress,
        amount,
      });
    }
  }
 
  await BasicTokenContract.compile(); // Compile
 
  return new BasicTokenContract(address);
}