All files / token Erc677Token.ts

84.7% Statements 72/85
25% Branches 1/4
64.51% Functions 20/31
84.33% Lines 70/83

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 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633                                                                                                    2x                                                                               2x                                                                                                                                   95x                 10x   10x   10x                                     10x 10x 10x     5x 15x                                                                                                                                               5x 15x 15x   15x   15x       15x                                           5x 15x 15x   15x   15x         15x                           5x 15x 15x                     5x                               5x                 15x                             15x 15x             95x     5x   5x       2x 2x 2x             62x                 16x   16x   16x                                     16x 16x 16x     2x 18x                                                                             12x     12x 12x                                                         2x 21x 21x   21x   21x       21x                                           2x 9x 9x   9x   9x         9x                           2x 9x 9x                       2x                               2x               10x                             10x 10x             62x    
import {
  ProvablePure,
  Bool,
  CircuitString,
  provablePure,
  Field,
  method,
  PublicKey,
  SmartContract,
  UInt64,
  Account,
  Permissions,
  State,
  state,
  Experimental,
  AccountUpdate,
  TokenContract,
  AccountUpdateForest,
} from 'o1js';
import { IERC20, IERC20Events, ERC20Events } from './Erc20Token.js';
import { OracleContract } from '../zkapp/OracleContract.js';
 
/**
 * Represents the events emitted by an ERC677 token contract.
 *
 * Extends the standard ERC20 events with an additional `TransferAndCall` event.
 * This event is used to signal a token transfer that also triggers a call to a
 * specified contract method.
 *
 * @type {IERC20Events & { TransferAndCall: ProvablePure<TransferAndCallArgs> }}
 */
export type IERC677Events = IERC20Events & {
  TransferAndCall: ProvablePure<{
    from: PublicKey;
    to: PublicKey;
    value: UInt64;
    data0: Field;
    data1: Field;
    data2: Field;
    data3: Field;
  }>;
};
 
/**
 * Defines the structure of a TransferAndCall event, typically used in the context of an ERC677 token contract.
 *
 * @type {Object}
 * @property {ProvablePure<TransferAndCallArgs>} TransferAndCall - A function that represents the event,
 *                                                              ensuring its pure (no side effects) and provable.
 */
const TransferAndCallEvent = {
  /**
   * The TransferAndCall event function.
   *
   */
  TransferAndCall: provablePure({
    /**
     * The address of the sender.
     *
     * @type {PublicKey}
     */
    from: PublicKey,
    /**
     * The address of the recipient.
     *
     * @type {PublicKey}
     */
    to: PublicKey,
    /**
     * The amount of tokens transferred.
     *
     * @type {UInt64}
     */
    value: UInt64,
 
    data0: Field,
    data1: Field,
    data2: Field,
    data3: Field,
  }),
};
/**
 * Exports an object containing all events emitted by an ERC677 token contract.
 *
 * Combines the standard ERC20 events with the `TransferAndCall` event, providing
 * a comprehensive representation of token transfer activities and contract calls.
 *
 * @type {IERC677Events}
 * @readonly
 */
export const ERC677Events: IERC677Events = {
  ...ERC20Events,
  ...TransferAndCallEvent,
};
/**
 * Defines the interface for an ERC677 token contract.
 *
 * Extends the standard ERC20 interface with the additional `transferAndCall` method,
 * enabling token transfers that also trigger contract calls.
 *
 * @abstract
 * @extends {IERC20}
 */
export abstract class IERC677 extends IERC20 {
  /**
   * Transfers tokens to a recipient and calls a contract method.
   *
   * @param {PublicKey} to - The address of the recipient.
   * @param {UInt64} value - The amount of tokens to transfer.
   * @param {Field} data0 - The first additional field to be passed to the contract method, if applicable.
   * @param {Field} data1 - The second additional field to be passed to the contract method, if applicable.
   * @param {Field} data2 - The third additional field to be passed to the contract method, if applicable.
   * @param {Field} data3 - The fourth additional field to be passed to the contract method, if applicable.
   * @returns {Bool} - True if the transfer and call were successful, false otherwise.
   * @emits Transfer - Emitted when the transfer is successful.
   */
  abstract transferAndCall(
    to: PublicKey,
    value: UInt64,
    data0: Field,
    data1: Field,
    data2: Field,
    data3: Field
  ): Promise<void>; // emits "Transfer" event
  /**
   * The events emitted by the contract.
   *
   * @type {IERC677Events}
   * @readonly
   */
  events: IERC677Events;
}
/**
 * Builds and returns an instance of an ERC677 token contract.
 *
 * @param {PublicKey} address - The contract address.
 * @param {string} name - The token name.
 * @param {string} symbol - The token symbol.
 * @param {number} decimals - The number of decimals for token precision.
 * @returns {Promise<SmartContract & IERC677>} - A promise that resolves to the constructed contract instance.
 */
export async function buildERC677Contract(
  address: PublicKey,
  name: string,
  symbol: string,
  decimals: number
): Promise<TokenContract & IERC677> {
  /**
   * Internal class representing the ERC677 contract implementation.
   */
  class Erc677Contract extends TokenContract implements IERC677 {
    /**
     * 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 ERC677 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 ERC677 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
    }
 
    /**
     * Transfers tokens to a recipient and optionally calls a contract method.
     *
     * @param {PublicKey} to - The address of the recipient.
     * @param {UInt64} value - The amount of tokens to transfer.
     * @param data0 - The first additional field to be passed to the contract method, if applicable.
     * @param data1 - The second additional field to be passed to the contract method, if applicable.
     * @param data2 - The third additional field to be passed to the contract method, if applicable.
     * @param data3 - The fourth additional field to be passed to the contract method, if applicable.
     * @returns {Bool} - Returns `false` in the current implementation.
     * @emits TransferAndCall - Emitted when the transfer is successful.
     */
    @method async transferAndCall(
      to: PublicKey,
      value: UInt64,
      data0: Field,
      data1: Field,
      data2: Field,
      data3: Field
    ) {
 
      this.internal.send({
        from: this.sender.getAndRequireSignature(),
        to,
        amount: value,
      });
      // this.emitEvent('TransferAndCall', {
      //   from: this.sender.getAndRequireSignature(),
      //   to,
      //   value,
      //   data0,
      //   data1,
      //   data2,
      //   data3,
      // });
 
      const oracleContract = new OracleContract(to);
      await oracleContract.oracleRequest(data0, data1, data2, data3);
 
      // we don't have to check the balance of the sender -- this is done by the zkApp protocol
    }
    /**
     * Events emitted by the contract.
     */
    events = ERC677Events;
  }
 
  await Erc677Contract.compile(); // Compile
 
  return new Erc677Contract(address);
}
 
export class SErc677Contract extends TokenContract implements IERC677 {
  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(SErc677Contract.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 ERC677 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(SErc677Contract.staticName);
  }
  /**
   * @returns The symbol of the token, as a CircuitString.
   * @remarks
   * This method adheres to the ERC677 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(SErc677Contract.staticSymbol);
  }
  /**
   * @returns The number of decimals used to represent token amounts, as a Field.
   * @todo Should be UInt8 when available.
   */
  decimals(): Field {
    return Field(SErc677Contract.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
  }
 
  /**
   * Transfers tokens to a recipient and optionally calls a contract method.
   *
   * @param {PublicKey} to - The address of the recipient.
   * @param {UInt64} value - The amount of tokens to transfer.
   * @param data0 - The first additional field to be passed to the contract method, if applicable.
   * @param data1 - The second additional field to be passed to the contract method, if applicable.
   * @param data2 - The third additional field to be passed to the contract method, if applicable.
   * @param data3 - The fourth additional field to be passed to the contract method, if applicable.
   * @returns {Bool} - Returns `false` in the current implementation.
   * @emits TransferAndCall - Emitted when the transfer is successful.
   */
  @method async transferAndCall(
    to: PublicKey,
    value: UInt64,
    data0: Field,
    data1: Field,
    data2: Field,
    data3: Field
  ) {
    this.internal.send({
      from: this.sender.getAndRequireSignature(),
      to,
      amount: value,
    });
    // this.emitEvent('TransferAndCall', {
    //   from: this.sender,
    //   to,
    //   value,
    //   data0,
    //   data1,
    //   data2,
    //   data3,
    // });
 
    const oracleContract = new OracleContract(to);
    await oracleContract.oracleRequest(data0, data1, data2, data3);
 
    // we don't have to check the balance of the sender -- this is done by the zkApp protocol
  }
  /**
   * Events emitted by the contract.
   */
  events = ERC677Events;
}