All files / token Erc20Token.ts

82.89% Statements 63/76
25% Branches 1/4
62.06% Functions 18/29
82.43% Lines 61/74

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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613                                                                                                                      3x                                                                                                                                                                                                                                                                                                                               86x                 10x   10x   10x                                     10x 10x 10x     5x 23x                                                                             8x     8x 8x                                                       5x 27x 27x   27x   27x       27x                                           5x 18x 18x   18x   18x         18x                           5x 18x 18x                     5x             86x     5x   5x       3x 3x 3x             60x                 10x   10x   10x                                     10x 10x 10x     3x 11x                                                                                                                                               3x 11x 11x   11x   11x       11x                                           3x 11x 11x   11x   11x         11x                           3x 11x 11x                     3x             60x    
import {
  ProvablePure,
  Bool,
  CircuitString,
  provablePure,
  Field,
  method,
  PublicKey,
  SmartContract,
  UInt64,
  Account,
  Permissions,
  State,
  state,
  TokenContract,
  AccountUpdateForest,
  AccountUpdate,
} from 'o1js';
 
/**
 * Represents the events emitted by an ERC20 token contract.
 *
 * @remarks
 * This type defines the structure of events that signal important state changes within the contract,
 * allowing external observers to track token transfers and approvals.
 */
export type IERC20Events = {
  /**
   * Emitted when tokens are transferred.
   *
   * @param from The address of the sender.
   * @param to The address of the recipient.
   * @param value The amount of tokens transferred.
   */
  Transfer: ProvablePure<{
    from: PublicKey;
    to: PublicKey;
    value: UInt64;
  }>;
  /**
   * Emitted when an allowance is approved.
   *
   * @param owner The address of the token owner.
   * @param spender The address of the spender who has been granted allowance.
   * @param value The amount of tokens approved.
   */
  Approval: ProvablePure<{
    owner: PublicKey;
    spender: PublicKey;
    value: UInt64;
  }>;
};
 
/**
 * An instance of the `IERC20Events` type, providing concrete event definitions for ERC20 token contracts.
 *
 * @remarks
 * This object can be used to subscribe to and handle these events within your application.
 */
export const ERC20Events: IERC20Events = {
  /**
   * Emitted when tokens are transferred.
   */
  Transfer: provablePure({
    from: PublicKey,
    to: PublicKey,
    value: UInt64,
  }),
  /**
   * Emitted when an allowance is approved.
   */
  Approval: provablePure({
    owner: PublicKey,
    spender: PublicKey,
    value: UInt64,
  }),
};
 
/**
 * Represents a standard interface for fungible tokens, implementing the ERC20 standard.
 *
 * @remarks
 * This abstract class defines a set of functions that tokens must implement to be compatible with
 * the ERC20 standard. It provides basic functionality for tracking token balances, transfers, and
 * approvals.
 *
 * @example
 * ```typescript
 * class MyToken implements IERC20 {
 *   // Implementation of IERC20 methods
 * }
 *
 */
export abstract class IERC20 {
  /**
   * @optional
   * @returns The name of the token, as a CircuitString.
   */
  abstract name?: () => CircuitString;
  /**
   * @optional
   * @returns The symbol of the token, as a CircuitString.
   */
  abstract symbol?: () => CircuitString;
  /**
   * @optional
   * @returns The number of decimals used to represent token amounts, as a Field.
   * @todo Should be UInt8 when available.
   */
  abstract decimals?: () => Field; // TODO: should be UInt8 which doesn't exist yet
  /**
   * @returns The total token supply, as a UInt64.
   */
  abstract totalSupply(): UInt64;
 
  /**
   * @param owner The address of the token owner.
   * @returns The balance of the owner, as a UInt64.
   */
  abstract balanceOf(owner: PublicKey | AccountUpdate): Promise<UInt64>;
  /**
   * @param owner The address of the token owner.
   * @param spender The address of the spender.
   * @returns The amount of tokens approved for the spender to spend on behalf of the owner, as a UInt64.
   */
  abstract allowance(owner: PublicKey, spender: PublicKey): UInt64;
 
  /**
   * 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, 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>;
 
  /**
   * @method
   * @param from The address to transfer tokens from.
   * @param to The address to transfer tokens to.
   * @param value The amount of tokens to transfer.
   * @returns True if the transfer was successful, false otherwise.
   * @emits Transfer
   *
   * @remarks
   * mutations which need @method
   */
  abstract transferFrom(
    from: PublicKey,
    to: PublicKey,
    value: UInt64
  ): Promise<void>; // emits "Transfer" event
 
  /**
   * @method
   * @param spender The address to approve as a spender.
   * @param value The amount of tokens to approve.
   * @returns True if the approval was successful, false otherwise.
   * @emits Approval
   *
   * @remarks
   * mutations which need @method
   */
  abstract approveSpend(spender: PublicKey, value: UInt64): Promise<void>; // emits "Approve" event
 
  /**
   * Events emitted by the contract.
   */
  events: IERC20Events;
}
 
// NotFixed
 
/**
 * Constructs and deploys an ERC20 token contract.
 *
 * @remarks
 * This function creates a new contract class that implements the `IERC20` interface, compiles it, and deploys it to the blockchain.
 * The returned contract instance can be used to interact with the token's functionality.
 *
 * @example
 * ```typescript
 * const myToken = await buildERC20Contract(address, 'MyToken', 'MTK', 18);
 * // Interact with the token contract using the `myToken` instance
 * ```
 *
 * @param address The address of the token contract on the blockchain.
 * @param name The name of the token.
 * @param symbol The symbol of the token.
 * @param decimals The number of decimals used to represent token amounts.
 * @returns A promise that resolves to the deployed contract instance.
 */
export async function buildERC20Contract(
  address: PublicKey,
  name: string,
  symbol: string,
  decimals: number
): Promise<TokenContract & IERC20> {
  /**
   * Represents an ERC20 token contract implementation.
   *
   * @remarks
   * This class extends the `SmartContract` class and implements the `IERC20` interface to provide core ERC20 token functionality.
   * It manages token balances, transfers, and approvals, adhering to the ERC20 standard.
   *
   */
  class Erc20Contract extends TokenContract implements IERC20 {
    /**
     * Stores the total amount of tokens in circulation.
     *
     * @type {State<UInt64>}
     */
    @state(UInt64) totalAmountInCirculation = State<UInt64>();
 
    /**
     * Deploys the contract to the blockchain and configures permissions.
     *
     * @remarks
     * This method sets up proof-based permissions for sensitive actions.
     */
    public async deploy() {
      await super.deploy();
 
      const permissionToEdit = Permissions.proof();
 
      this.account.permissions.set({
        ...Permissions.default(),
        editState: permissionToEdit,
        setTokenSymbol: permissionToEdit,
        send: permissionToEdit,
        receive: permissionToEdit,
      });
    }
 
    /**
     * 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);
    }
 
    /**
     * @returns The name of the token, as a CircuitString.
     * @remarks
     * This method adheres to the ERC20 standard for retrieving the token's name.
     * It converts the stored string name into a CircuitString for compatibility with zkApp operations.
     */
    name(): CircuitString {
      return CircuitString.fromString(name);
    }
    /**
     * @returns The symbol of the token, as a CircuitString.
     * @remarks
     * This method adheres to the ERC20 standard for retrieving the token's symbol.
     * It converts the stored string symbol into a CircuitString for compatibility with zkApp operations.
     */
    symbol(): CircuitString {
      return CircuitString.fromString(symbol);
    }
    /**
     * @returns The number of decimals used to represent token amounts, as a Field.
     * @todo Should be UInt8 when available.
     */
    decimals(): Field {
      return Field(decimals);
    }
    /**
     * @returns The total token supply, as a UInt64.
     * @remarks
     * This method accesses the `totalAmountInCirculation` state variable to provide the current token supply.
     */
    totalSupply(): UInt64 {
      return this.totalAmountInCirculation.get();
    }
 
    async balanceOf(owner: PublicKey | AccountUpdate): Promise<UInt64> {
      let update =
        owner instanceof PublicKey
          ? AccountUpdate.create(owner, this.deriveTokenId())
          : owner;
      await this.approveAccountUpdate(update);
      return update.account.balance.getAndRequireEquals();
    }
    /**
     * @param owner The address of the token owner.
     * @param spender The address of the spender.
     * @returns The amount of tokens approved for the spender, as a UInt64.
     * @todo Implement allowance functionality to enable approved spending.
     */
    allowance(owner: PublicKey, spender: PublicKey): UInt64 {
      // TODO: implement allowances
      return UInt64.zero;
    }
 
    /**
     * 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, 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);
    }
 
    /**
     * @method
     * @param from The address to transfer tokens from.
     * @param to The address to transfer tokens to.
     * @param value The amount of tokens to transfer.
     * @returns True if the transfer was successful, false otherwise.
     * @emits Transfer
     * @remarks
     * Similar to `transfer()`, but allows transferring tokens from a specified address, often for approved spending.
     * Also relies on the zkApp protocol for secure balance checks and emits a Transfer event.
     */
    @method async transferFrom(from: PublicKey, to: PublicKey, value: UInt64) {
      this.internal.send({ from, to, amount: value });
      this.emitEvent('Transfer', { from, to, value });
      // we don't have to check the balance of the sender -- this is done by the zkApp protocol
    }
    /**
     * @method
     * @param spender The address to approve as a spender.
     * @param value The amount of tokens to approve.
     * @returns True if the approval was successful, false otherwise.
     * @emits Approval
     * @todo Implement allowance functionality to enable token approvals.
     */
    @method async approveSpend(spender: PublicKey, value: UInt64) {
      // TODO: implement allowances
    }
 
    /**
     * Events emitted by the contract to signal important state changes.
     */
    events = ERC20Events;
  }
 
  await Erc20Contract.compile(); // Compile
 
  return new Erc20Contract(address);
}
 
export class SErc20Contract extends TokenContract implements IERC20 {
  static staticSymbol = '';
  static staticName = '';
  static staticDecimals = 0;
 
  /**
   * Stores the total amount of tokens in circulation.
   *
   * @type {State<UInt64>}
   */
  @state(UInt64) totalAmountInCirculation = State<UInt64>();
 
  /**
   * Deploys the contract to the blockchain and configures permissions.
   *
   * @remarks
   * This method sets up proof-based permissions for sensitive actions.
   */
  public async deploy() {
    await super.deploy();
 
    const permissionToEdit = Permissions.proof();
 
    this.account.permissions.set({
      ...Permissions.default(),
      editState: permissionToEdit,
      setTokenSymbol: permissionToEdit,
      send: permissionToEdit,
      receive: permissionToEdit,
    });
  }
 
  /**
   * 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(SErc20Contract.staticSymbol);
    this.totalAmountInCirculation.set(UInt64.zero);
  }
 
  @method async approveBase(forest: AccountUpdateForest) {
    this.checkZeroBalanceChange(forest);
  }
 
  /**
   * @returns The name of the token, as a CircuitString.
   * @remarks
   * This method adheres to the ERC20 standard for retrieving the token's name.
   * It converts the stored string name into a CircuitString for compatibility with zkApp operations.
   */
  name(): CircuitString {
    return CircuitString.fromString(SErc20Contract.staticName);
  }
  /**
   * @returns The symbol of the token, as a CircuitString.
   * @remarks
   * This method adheres to the ERC20 standard for retrieving the token's symbol.
   * It converts the stored string symbol into a CircuitString for compatibility with zkApp operations.
   */
  symbol(): CircuitString {
    return CircuitString.fromString(SErc20Contract.staticSymbol);
  }
  /**
   * @returns The number of decimals used to represent token amounts, as a Field.
   * @todo Should be UInt8 when available.
   */
  decimals(): Field {
    return Field(SErc20Contract.staticDecimals);
  }
  /**
   * @returns The total token supply, as a UInt64.
   * @remarks
   * This method accesses the `totalAmountInCirculation` state variable to provide the current token supply.
   */
  totalSupply(): UInt64 {
    return this.totalAmountInCirculation.get();
  }
 
  async balanceOf(owner: PublicKey | AccountUpdate): Promise<UInt64> {
    let update =
      owner instanceof PublicKey
        ? AccountUpdate.create(owner, this.deriveTokenId())
        : owner;
    await this.approveAccountUpdate(update);
    return update.account.balance.getAndRequireEquals();
  }
 
  /**
   * @param owner The address of the token owner.
   * @param spender The address of the spender.
   * @returns The amount of tokens approved for the spender, as a UInt64.
   * @todo Implement allowance functionality to enable approved spending.
   */
  allowance(owner: PublicKey, spender: PublicKey): UInt64 {
    // TODO: implement allowances
    return UInt64.zero;
  }
 
  /**
   * 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, 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);
  }
 
  /**
   * @method
   * @param from The address to transfer tokens from.
   * @param to The address to transfer tokens to.
   * @param value The amount of tokens to transfer.
   * @returns True if the transfer was successful, false otherwise.
   * @emits Transfer
   * @remarks
   * Similar to `transfer()`, but allows transferring tokens from a specified address, often for approved spending.
   * Also relies on the zkApp protocol for secure balance checks and emits a Transfer event.
   */
  @method async transferFrom(from: PublicKey, to: PublicKey, value: UInt64) {
    this.internal.send({ from, to, amount: value });
    this.emitEvent('Transfer', { from, to, value });
    // we don't have to check the balance of the sender -- this is done by the zkApp protocol
  }
  /**
   * @method
   * @param spender The address to approve as a spender.
   * @param value The amount of tokens to approve.
   * @returns True if the approval was successful, false otherwise.
   * @emits Approval
   * @todo Implement allowance functionality to enable token approvals.
   */
  @method async approveSpend(spender: PublicKey, value: UInt64) {
    // TODO: implement allowances
  }
 
  /**
   * Events emitted by the contract to signal important state changes.
   */
  events = ERC20Events;
}