Token holder contract, manage swap and liquidity remove functions

Hierarchy

  • SmartContract
    • PoolTokenHolder

Implements

  • IPool

Constructors

  • Parameters

    • address: PublicKey
    • OptionaltokenId: Field

    Returns PoolTokenHolder

Properties

address: PublicKey
events: {
    subWithdrawLiquidity: typeof SubWithdrawLiquidityEvent;
    swap: typeof SwapEvent;
    upgrade: typeof UpdateVerificationKeyEvent;
    withdrawLiquidity: typeof WithdrawLiquidityEvent;
} = ...

List of pool token holder events

poolFactory: State<PublicKey> = ...

Pool factory contract address

sender: {
    self: SmartContract;
    getAndRequireSignature(): PublicKey;
    getUnconstrained(): PublicKey;
}

Type declaration

  • self: SmartContract
  • getAndRequireSignature:function
    • Return a public key that is forced to sign this transaction.

      Note: This doesn't prove that the return value is the transaction sender, but it proves that whoever created the transaction controls the private key associated with the returned public key.

      Returns PublicKey

  • getUnconstrained:function
    • The public key of the current transaction's sender account.

      Throws an error if not inside a transaction, or the sender wasn't passed in.

      Warning: The fact that this public key equals the current sender is not part of the proof. A malicious prover could use any other public key without affecting the validity of the proof.

      Consider using this.sender.getAndRequireSignature() if you need to prove that the sender controls this account.

      Returns PublicKey

token0: State<PublicKey> = ...

Address of first token in the pool (ordered by address) PublicKey.empty() in case of native mina

token1: State<PublicKey> = ...

Address of second token in the pool Can't be empty

tokenId: Field
_methodMetadata?: Record<string, {
    actions: number;
    digest: string;
    gates: Gate[];
    proofs: ProofClass[];
    rows: number;
}>
_methods?: MethodInterface[]
_provers?: Prover[]
_verificationKey?: {
    data: string;
    hash: Field;
}
FactoryContract: (new (...args: any) => PoolFactoryBase) = PoolFactory

We declare the factory contract as a static property so that it can be easily replaced in case of factory upgrade

Type declaration

    • new (...args): PoolFactoryBase
    • We declare the factory contract as a static property so that it can be easily replaced in case of factory upgrade

      Parameters

      • Rest...args: any

      Returns PoolFactoryBase

Accessors

  • get account(): Account
  • Current account of the SmartContract.

    Returns Account

  • get balance(): {
        addInPlace(x:
            | string
            | number
            | bigint
            | UInt32
            | UInt64
            | Int64): void;
        subInPlace(x:
            | string
            | number
            | bigint
            | UInt32
            | UInt64
            | Int64): void;
    }
  • Balance of this SmartContract.

    Returns {
        addInPlace(x:
            | string
            | number
            | bigint
            | UInt32
            | UInt64
            | Int64): void;
        subInPlace(x:
            | string
            | number
            | bigint
            | UInt32
            | UInt64
            | Int64): void;
    }

    • addInPlace:function
      • Parameters

        • x:
              | string
              | number
              | bigint
              | UInt32
              | UInt64
              | Int64

        Returns void

    • subInPlace:function
      • Parameters

        • x:
              | string
              | number
              | bigint
              | UInt32
              | UInt64
              | Int64

        Returns void

  • get currentSlot(): CurrentSlot
  • Current global slot on the network. This is the slot at which this transaction is included in a block. Since we cannot know this value at the time of transaction construction, this only has the assertBetween() method but no get() (impossible to implement) or assertEquals() (confusing, because the developer can't know the exact slot at which this will be included either)

    Returns CurrentSlot

  • get network(): Network
  • Current network state of the SmartContract.

    Returns Network

  • get self(): AccountUpdate
  • Returns the current AccountUpdate associated to this SmartContract.

    Returns AccountUpdate

Methods

  • Approve an account update or tree / forest of updates. Doing this means you include the account update in the zkApp's public input, which allows you to read and use its content in a proof, make assertions about it, and modify it.

    `@method` myApprovingMethod(update: AccountUpdate) {
    this.approve(update);

    // read balance on the account (for example)
    let balance = update.account.balance.getAndRequireEquals();
    }

    Under the hood, "approving" just means that the account update is made a child of the zkApp in the tree of account updates that forms the transaction. Similarly, if you pass in an AccountUpdateTree, the entire tree will become a subtree of the zkApp's account update.

    Passing in a forest is a bit different, because it means you set the entire children of the zkApp's account update at once. approve() will fail if the zkApp's account update already has children, to prevent you from accidentally excluding important information from the public input.

    Parameters

    • update: AccountUpdateForest | AccountUpdate | AccountUpdateTree

    Returns void

  • Emits an event. Events will be emitted as a part of the transaction and can be collected by archive nodes.

    Type Parameters

    • K extends
          | "upgrade"
          | "swap"
          | "withdrawLiquidity"
          | "subWithdrawLiquidity"

    Parameters

    • type: K
    • event: any

    Returns void

  • Conditionally emits an event.

    Events will be emitted as a part of the transaction and can be collected by archive nodes.

    Type Parameters

    • K extends
          | "upgrade"
          | "swap"
          | "withdrawLiquidity"
          | "subWithdrawLiquidity"

    Parameters

    • condition: Bool
    • type: K
    • event: any

    Returns void

  • Asynchronously fetches events emitted by this SmartContract and returns an array of events with their corresponding types.

    Parameters

    • Optionalstart: UInt32

      The start height of the events to fetch.

    • Optionalend: UInt32

      The end height of the events to fetch. If not provided, fetches events up to the latest height.

    Returns Promise<{
        blockHash: string;
        blockHeight: UInt32;
        chainStatus: string;
        event: {
            data: ProvablePure<any>;
            transactionInfo: {
                transactionHash: string;
                transactionMemo: string;
                transactionStatus: string;
            };
        };
        globalSlot: UInt32;
        parentBlockHash: string;
        type: string;
    }[]>

    A promise that resolves to an array of objects, each containing the event type and event data for the specified range.

    If there is an error fetching events from the Mina network.

    const startHeight = UInt32.from(1000);
    const endHeight = UInt32.from(2000);
    const events = await myZkapp.fetchEvents(startHeight, endHeight);
    console.log(events);
  • SmartContract.init() will be called only when a SmartContract will be first deployed, not for redeployment. This method can be overridden as follows

    class MyContract extends SmartContract {
    init() {
    super.init();
    this.account.permissions.set(...);
    this.x.set(Field(1));
    }
    }

    Returns void

  • Same as SmartContract.self but explicitly creates a new AccountUpdate.

    Parameters

    • OptionalmethodName: string

    Returns AccountUpdate

  • Use this command if the account update created by this SmartContract should be signed by the account owner, instead of authorized with a proof.

    Note that the smart contract's Permissions determine which updates have to be (can be) authorized by a signature.

    If you only want to avoid creating proofs for quicker testing, we advise you to use LocalBlockchain({ proofsEnabled: false }) instead of requireSignature(). Setting proofsEnabled to false allows you to test your transactions with the same authorization flow as in production, with the only difference being that quick mock proofs are filled in instead of real proofs.

    Returns void

  • Parameters

    • args: {
          amount: number | bigint | UInt64;
          to: PublicKey | SmartContract | AccountUpdate;
      }
      • amount: number | bigint | UInt64
      • to: PublicKey | SmartContract | AccountUpdate

    Returns AccountUpdate

  • Use this command if the account update created by this SmartContract should have no authorization on it, instead of being authorized with a proof.

    WARNING: This is a method that should rarely be useful. If you want to disable proofs for quicker testing, take a look at LocalBlockchain({ proofsEnabled: false }), which causes mock proofs to be created and doesn't require changing the authorization flow.

    Returns void

  • Don't call this method directly, use withdrawLiquidityToken for token 0

    Parameters

    • sender: PublicKey
    • liquidityAmount: UInt64
    • amountToken1Min: UInt64
    • reserveToken1Min: UInt64
    • supplyMax: UInt64

    Returns Promise<UInt64>

  • Swap from mina to token

    Parameters

    • frontend: PublicKey

      address who collect the frontend fees

    • taxFeeFrontend: UInt64

      fees applied by the frontend

    • amountMinaIn: UInt64

      amount of mina to swap

    • amountTokenOutMin: UInt64

      minimum token to received

    • balanceInMax: UInt64

      minimum balance of mina in the pool

    • balanceOutMin: UInt64

      maximum balance of token in the pool

    Returns Promise<void>

  • Swap from token to another token

    Parameters

    • frontend: PublicKey

      address who collect the frontend fees

    • taxFeeFrontend: UInt64

      fees applied by the frontend

    • amountTokenIn: UInt64

      amount of tokenIn to swap

    • amountTokenOutMin: UInt64

      minimum tokenOut to received

    • balanceInMax: UInt64

      minimum balance of tokenIn in the pool

    • balanceOutMin: UInt64

      maximum balance of tokenOut in the pool

    Returns Promise<void>

  • Withdraw liquidity from the mina/token pool The reserves min and supply max permit concurrent call, use slippage mechanism to calculate it

    Parameters

    • liquidityAmount: UInt64

      amount of liquidity to withdraw

    • amountMinaMin: UInt64

      minimum amount of mina to receive

    • amountTokenMin: UInt64

      minimum amount of token to receive

    • reserveMinaMin: UInt64

      reserve min of mina in the pool

    • reserveTokenMin: UInt64

      reserve min of token in the pool

    • supplyMax: UInt64

      maximum liquidity in the pool

    Returns Promise<void>

  • Withdraw liquidity from the token/token pool The reserves min and supply max permit concurrent call, use slippage mechanism to calculate it

    Parameters

    • liquidityAmount: UInt64

      amount of liquidity to withdraw

    • amountToken0Min: UInt64
    • amountToken1Min: UInt64
    • reserveToken0Min: UInt64
    • reserveToken1Min: UInt64
    • supplyMax: UInt64

      maximum liquidity in the pool

    Returns Promise<void>

  • This function is run internally before compiling a smart contract, to collect metadata about what each of your smart contract methods does.

    For external usage, this function can be handy because calling it involves running all methods in the same "mode" as compile() does, so it serves as a quick-to-run check for whether your contract can be compiled without errors, which can greatly speed up iterating.

    analyzeMethods() will also return the number of rows of each of your method circuits (i.e., the number of constraints in the underlying proof system), which is a good indicator for circuit size and the time it will take to create proofs. To inspect the created circuit in detail, you can look at the returned gates.

    Note: If this function was already called before, it will short-circuit and just return the metadata collected the first time.

    Parameters

    • Optional__namedParameters: {
          printSummary?: boolean;
      }
      • OptionalprintSummary?: boolean

    Returns Promise<Record<string, {
        actions: number;
        digest: string;
        gates: Gate[];
        proofs: ProofClass[];
        rows: number;
    }>>

    an object, keyed by method name, each entry containing:

    • rows the size of the constraint system created by this method
    • digest a digest of the method circuit
    • actions the number of actions the method dispatches
    • gates the constraint system, represented as an array of gates
  • Compile your smart contract.

    This generates both the prover functions, needed to create proofs for running @methods, and the verification key, needed to deploy your zkApp.

    Although provers and verification key are returned by this method, they are also cached internally and used when needed, so you don't actually have to use the return value of this function.

    Under the hood, "compiling" means calling into the lower-level Pickles and Kimchi libraries to create multiple prover & verifier indices (one for each smart contract method as part of a "step circuit" and one for the "wrap circuit" which recursively wraps it so that proofs end up in the original finite field). These are fairly expensive operations, so expect compiling to take at least 20 seconds, up to several minutes if your circuit is large or your hardware is not optimal for these operations.

    Parameters

    • Optional__namedParameters: {
          cache?: Cache;
          forceRecompile?: boolean;
      }
      • Optionalcache?: Cache
      • OptionalforceRecompile?: boolean

    Returns Promise<{
        provers: Prover[];
        verificationKey: {
            data: string;
            hash: Field;
        };
        verify: ((statement: Statement<FieldConst>, proof: unknown) => Promise<boolean>);
    }>

  • Computes a hash of your smart contract, which will reliably change whenever one of your method circuits changes. This digest is quick to compute. it is designed to help with deciding whether a contract should be re-compiled or a cached verification key can be used.

    Returns Promise<string>

    the digest, as a hex string

  • The maximum number of proofs that are verified by any of the zkApp methods. This is an internal parameter needed by the proof system.

    Returns Promise<0 | 1 | 2>

  • Returns a Proof type that belongs to this SmartContract.

    Returns {
        provable: {
            check: ((value: Proof<any, any>) => void);
            fromFields: ((fields: Field[], aux: any[]) => Proof<any, any>);
            fromValue: ((x: Proof<any, any> | ProofValue<any, any>) => Proof<any, any>);
            toAuxiliary: ((value?: Proof<any, any>) => any[]);
            toCanonical?: ((x: Proof<any, any>) => Proof<any, any>);
            toFields: ((value: Proof<any, any>) => Field[]);
            toValue: ((x: Proof<any, any>) => ProofValue<any, any>);
            sizeInFields(): number;
        };
        publicInputType: Omit<Provable<{
            accountUpdate: Field;
            calls: Field;
        }, {
            accountUpdate: bigint;
            calls: bigint;
        }>, "fromFields"> & {
            fromFields: ((fields: Field[]) => {
                accountUpdate: Field;
                calls: Field;
            });
        } & {
            empty: (() => {
                accountUpdate: Field;
                calls: Field;
            });
            fromJSON: ((x: {
                accountUpdate: string;
                calls: string;
            }) => {
                accountUpdate: Field;
                calls: Field;
            });
            toInput: ((x: {
                accountUpdate: Field;
                calls: Field;
            }) => {
                fields?: Field[];
                packed?: [Field, number][];
            });
            toJSON: ((x: {
                accountUpdate: Field;
                calls: Field;
            }) => {
                accountUpdate: string;
                calls: string;
            });
        };
        publicOutputType: ProvablePureExtended<undefined, undefined, null>;
        tag: (() => typeof SmartContract);
        _proofFromBase64(proofString: string, maxProofsVerified: 0 | 1 | 2): unknown;
        _proofToBase64(proof: unknown, maxProofsVerified: 0 | 1 | 2): string;
        dummy<Input, OutPut>(publicInput: Input, publicOutput: OutPut, maxProofsVerified: 0 | 1 | 2, domainLog2?: number): Promise<Proof<Input, OutPut>>;
        fromJSON<S>(this: S, __namedParameters: JsonProof): Promise<Proof<InferProvable<S["publicInputType"]>, InferProvable<S["publicOutputType"]>>>;
        publicFields(value: ProofBase<any, any>): {
            input: Field[];
            output: Field[];
        };
        new (__namedParameters: {
            maxProofsVerified: 0 | 1 | 2;
            proof: unknown;
            publicInput: ZkappPublicInput;
            publicOutput: undefined;
        }): {
            maxProofsVerified: 0 | 1 | 2;
            proof: unknown;
            publicInput: ZkappPublicInput;
            publicOutput: undefined;
            shouldVerify: Bool;
            declare(): boolean;
            publicFields(): {
                input: Field[];
                output: Field[];
            };
            toJSON(): JsonProof;
            verify(): void;
            verifyIf(condition: Bool): void;
        };
    }

      • new (__namedParameters): {
            maxProofsVerified: 0 | 1 | 2;
            proof: unknown;
            publicInput: ZkappPublicInput;
            publicOutput: undefined;
            shouldVerify: Bool;
            declare(): boolean;
            publicFields(): {
                input: Field[];
                output: Field[];
            };
            toJSON(): JsonProof;
            verify(): void;
            verifyIf(condition: Bool): void;
        }
      • Parameters

        • __namedParameters: {
              maxProofsVerified: 0 | 1 | 2;
              proof: unknown;
              publicInput: ZkappPublicInput;
              publicOutput: undefined;
          }
          • maxProofsVerified: 0 | 1 | 2
          • proof: unknown
          • publicInput: ZkappPublicInput
          • publicOutput: undefined

        Returns {
            maxProofsVerified: 0 | 1 | 2;
            proof: unknown;
            publicInput: ZkappPublicInput;
            publicOutput: undefined;
            shouldVerify: Bool;
            declare(): boolean;
            publicFields(): {
                input: Field[];
                output: Field[];
            };
            toJSON(): JsonProof;
            verify(): void;
            verifyIf(condition: Bool): void;
        }

        • maxProofsVerified: 0 | 1 | 2
        • proof: unknown
        • publicInput: ZkappPublicInput
        • publicOutput: undefined
        • shouldVerify: Bool
        • declare:function
          • Returns boolean

        • publicFields:function
          • Returns {
                input: Field[];
                output: Field[];
            }

            • input: Field[]
            • output: Field[]
        • toJSON:function
          • Returns JsonProof

        • verify:function
          • Returns void

        • verifyIf:function
          • Parameters

            • condition: Bool

            Returns void

    • Readonlyprovable: {
          check: ((value: Proof<any, any>) => void);
          fromFields: ((fields: Field[], aux: any[]) => Proof<any, any>);
          fromValue: ((x: Proof<any, any> | ProofValue<any, any>) => Proof<any, any>);
          toAuxiliary: ((value?: Proof<any, any>) => any[]);
          toCanonical?: ((x: Proof<any, any>) => Proof<any, any>);
          toFields: ((value: Proof<any, any>) => Field[]);
          toValue: ((x: Proof<any, any>) => ProofValue<any, any>);
          sizeInFields(): number;
      }
      • check: ((value: Proof<any, any>) => void)
          • (value): void
          • Parameters

            • value: Proof<any, any>

            Returns void

      • fromFields: ((fields: Field[], aux: any[]) => Proof<any, any>)
          • (fields, aux): Proof<any, any>
          • Parameters

            • fields: Field[]
            • aux: any[]

            Returns Proof<any, any>

      • fromValue: ((x: Proof<any, any> | ProofValue<any, any>) => Proof<any, any>)
          • (x): Proof<any, any>
          • Parameters

            • x: Proof<any, any> | ProofValue<any, any>

            Returns Proof<any, any>

      • toAuxiliary: ((value?: Proof<any, any>) => any[])
          • (value?): any[]
          • Parameters

            • Optionalvalue: Proof<any, any>

            Returns any[]

      • OptionaltoCanonical?: ((x: Proof<any, any>) => Proof<any, any>)
          • (x): Proof<any, any>
          • Parameters

            • x: Proof<any, any>

            Returns Proof<any, any>

      • toFields: ((value: Proof<any, any>) => Field[])
          • (value): Field[]
          • Parameters

            • value: Proof<any, any>

            Returns Field[]

      • toValue: ((x: Proof<any, any>) => ProofValue<any, any>)
          • (x): ProofValue<any, any>
          • Parameters

            • x: Proof<any, any>

            Returns ProofValue<any, any>

      • sizeInFields:function
        • Returns number

    • publicInputType: Omit<Provable<{
          accountUpdate: Field;
          calls: Field;
      }, {
          accountUpdate: bigint;
          calls: bigint;
      }>, "fromFields"> & {
          fromFields: ((fields: Field[]) => {
              accountUpdate: Field;
              calls: Field;
          });
      } & {
          empty: (() => {
              accountUpdate: Field;
              calls: Field;
          });
          fromJSON: ((x: {
              accountUpdate: string;
              calls: string;
          }) => {
              accountUpdate: Field;
              calls: Field;
          });
          toInput: ((x: {
              accountUpdate: Field;
              calls: Field;
          }) => {
              fields?: Field[];
              packed?: [Field, number][];
          });
          toJSON: ((x: {
              accountUpdate: Field;
              calls: Field;
          }) => {
              accountUpdate: string;
              calls: string;
          });
      }
    • publicOutputType: ProvablePureExtended<undefined, undefined, null>
    • tag: (() => typeof SmartContract)
        • (): typeof SmartContract
        • Returns typeof SmartContract

    • _proofFromBase64:function
      • Parameters

        • proofString: string
        • maxProofsVerified: 0 | 1 | 2

        Returns unknown

    • _proofToBase64:function
      • Parameters

        • proof: unknown
        • maxProofsVerified: 0 | 1 | 2

        Returns string

    • dummy:function
      • Type Parameters

        • Input
        • OutPut

        Parameters

        • publicInput: Input
        • publicOutput: OutPut
        • maxProofsVerified: 0 | 1 | 2
        • OptionaldomainLog2: number

        Returns Promise<Proof<Input, OutPut>>

    • fromJSON:function
      • Type Parameters

        • S extends Subclass<typeof Proof>

        Parameters

        • this: S
        • __namedParameters: JsonProof

        Returns Promise<Proof<InferProvable<S["publicInputType"]>, InferProvable<S["publicOutputType"]>>>

    • publicFields:function
      • Parameters

        • value: ProofBase<any, any>

        Returns {
            input: Field[];
            output: Field[];
        }

        • input: Field[]
        • output: Field[]
  • Parameters

    • run: (() => void)
        • (): void
        • Returns void

    Returns void

  • Manually set the verificaiton key.

    Parameters

    • verificationKey: {
          data: string;
          hash: string | Field;
      }
      • data: string
      • hash: string | Field

    Returns void