Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom token bridging #206

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v18.14.2
v22.9.0
Copy link
Member Author

@rpanic rpanic Oct 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about this one, v18 leads to very bad performance on apple silicon, maybe we can use v20 though

20,537 changes: 1,909 additions & 18,628 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"@proto-kit/module": "*",
"@proto-kit/protocol": "*",
"@proto-kit/sequencer": "*",
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"tsyringe": "^4.7.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"typescript-memoize": "^1.1.1"
},
"peerDependencies": {
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"tsyringe": "^4.7.0"
},
"devDependencies": {
Expand Down
2 changes: 2 additions & 0 deletions packages/common/src/config/ModuleContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,8 @@ export class ModuleContainer<
);
}

protected createSuperClassAliases(module: any) {}

/**
* This is a placeholder for individual modules to override.
* This method will be called whenever the underlying container fully
Expand Down
10 changes: 10 additions & 0 deletions packages/common/src/dummyVerificationKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Field, VerificationKey } from "o1js";

export function dummyVerificationKey() {
return new VerificationKey({
hash: Field(
"3392518251768960475377392625298437850623664973002200885669375116181514017494"
),
data: "AgIBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALsq7cojes8ZcUc9M9RbZY9U7nhj8KnfU3yTEgqjtXQbAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7Ku3KI3rPGXFHPTPUW2WPVO54Y/Cp31N8kxIKo7V0GwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuyrtyiN6zxlxRz0z1Ftlj1TueGPwqd9TfJMSCqO1dBsBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALsq7cojes8ZcUc9M9RbZY9U7nhj8KnfU3yTEgqjtXQbAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7Ku3KI3rPGXFHPTPUW2WPVO54Y/Cp31N8kxIKo7V0GwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuyrtyiN6zxlxRz0z1Ftlj1TueGPwqd9TfJMSCqO1dBsBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALsq7cojes8ZcUc9M9RbZY9U7nhj8KnfU3yTEgqjtXQbAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuyrtyiN6zxlxRz0z1Ftlj1TueGPwqd9TfJMSCqO1dBsBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALsq7cojes8ZcUc9M9RbZY9U7nhj8KnfU3yTEgqjtXQbAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7Ku3KI3rPGXFHPTPUW2WPVO54Y/Cp31N8kxIKo7V0GwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuyrtyiN6zxlxRz0z1Ftlj1TueGPwqd9TfJMSCqO1dBsBAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAC7Ku3KI3rPGXFHPTPUW2WPVO54Y/Cp31N8kxIKo7V0GwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuyrtyiN6zxlxRz0z1Ftlj1TueGPwqd9TfJMSCqO1dBsBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALsq7cojes8ZcUc9M9RbZY9U7nhj8KnfU3yTEgqjtXQbAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7Ku3KI3rPGXFHPTPUW2WPVO54Y/Cp31N8kxIKo7V0GwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuyrtyiN6zxlxRz0z1Ftlj1TueGPwqd9TfJMSCqO1dBs=",
});
}
42 changes: 42 additions & 0 deletions packages/common/src/events/ReplayingSingleUseEventEmitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { EventsRecord } from "./EventEmittingComponent";
import { EventEmitter } from "./EventEmitter";

/**
* Event Emitter variant that emits a certain event only once to a registered listener.
* Additionally, if a listener registers to a event that has already been emitted, it
* re-emits it to said listener.
* This pattern is especially useful for listening for inclusions of transactions.
* Those events will only occur once, and listeners could come too late to the party,
* so we need to make sure they get notified as well in those cases.
*/
export class ReplayingSingleUseEventEmitter<
Events extends EventsRecord,
> extends EventEmitter<Events> {
public emitted: Partial<Events> = {};

public emit<Key extends keyof Events>(
event: Key,
...parameters: Events[Key]
) {
super.emit(event, ...parameters);
this.emitted[event] = parameters;
this.listeners[event] = [];
}

public onAll(listener: (event: keyof Events, args: unknown[]) => void) {
Object.entries(this.emitted).forEach(([key, params]) => {
if (params !== undefined) listener(key, params);
});
super.onAll(listener);
}

public on<Key extends keyof Events>(
event: Key,
listener: (...args: Events[Key]) => void
) {
if (this.emitted[event] !== undefined) {
listener(...this.emitted[event]!);
}
super.on(event, listener);
}
}
1 change: 1 addition & 0 deletions packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ export * from "./trees/MerkleTreeStore";
export * from "./trees/InMemoryMerkleTreeStorage";
export * from "./trees/RollupMerkleTree";
export * from "./events/EventEmitterProxy";
export * from "./events/ReplayingSingleUseEventEmitter";
export * from "./trees/MockAsyncMerkleStore";
19 changes: 18 additions & 1 deletion packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@ export function requireTrue(
}
}

export function splitArray<T, K extends string | number>(
arr: T[],
split: (t: T) => K
): Record<K, T[] | undefined> {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const record = {} as { [Key in K]: T[] };
arr.forEach((element) => {
const k = split(element);
if (record[k] !== undefined) {
record[k].push(element);
} else {
record[k] = [element];
}
});
return record;
}

export function range(
startOrEnd: number,
endOrNothing?: number | undefined
Expand Down Expand Up @@ -52,7 +69,7 @@ export function reduceSequential<T, U>(
export function mapSequential<T, R>(
array: T[],
f: (element: T, index: number, array: T[]) => Promise<R>
) {
): Promise<R[]> {
return array.reduce<Promise<R[]>>(async (r, element, index, a) => {
const ret = await r;
const next = await f(element, index, a);
Expand Down
6 changes: 2 additions & 4 deletions packages/common/src/zkProgrammable/ZkProgrammable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ZkProgram, FlexibleProvablePure, Proof, Field, Provable } from "o1js";
import { Memoize } from "typescript-memoize";

import { log } from "../log";
import { dummyVerificationKey } from "../dummyVerificationKey";

import { MOCK_PROOF } from "./provableMethod";

Expand Down Expand Up @@ -75,10 +76,7 @@ export function verifyToMockable<PublicInput, PublicOutput>(
};
}

export const MOCK_VERIFICATION_KEY = {
data: "mock-verification-key",
hash: Field(0),
};
export const MOCK_VERIFICATION_KEY = dummyVerificationKey();

export function compileToMockable(
compile: Compile,
Expand Down
1 change: 1 addition & 0 deletions packages/common/src/zkProgrammable/provableMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type ArgumentTypes = (
export type DecoratedMethod = (...args: ArgumentTypes) => Promise<unknown>;

export const MOCK_PROOF = "mock-proof";
// (await Proof.dummy(Field(0), Field(0), 2)).proof as string;

export function toProver(
methodName: string,
Expand Down
2 changes: 1 addition & 1 deletion packages/deployment/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"@proto-kit/sdk": "*",
"@proto-kit/sequencer": "*",
"bullmq": "^3.15.8",
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"tsyringe": "^4.7.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/library/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"@proto-kit/module": "*",
"@proto-kit/protocol": "*",
"@proto-kit/sequencer": "*",
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"tsyringe": "^4.7.0"
},
"devDependencies": {
Expand Down
60 changes: 44 additions & 16 deletions packages/library/src/runtime/Withdrawals.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,63 @@
import { runtimeModule, RuntimeModule, state } from "@proto-kit/module";
import { State, StateMap, Withdrawal } from "@proto-kit/protocol";
import { Field, PublicKey } from "o1js";
import {
RuntimeEvents,
runtimeModule,
RuntimeModule,
state,
} from "@proto-kit/module";
import { StateMap, Withdrawal } from "@proto-kit/protocol";
import { Field, PublicKey, Struct } from "o1js";
import { inject } from "tsyringe";

import { UInt64 } from "../math/UInt64";

import { Balances, TokenId } from "./Balances";
import { Balances } from "./Balances";

export class WithdrawalKey extends Struct({
index: Field,
tokenId: Field,
}) {}

export class WithdrawalEvent extends Struct({
key: WithdrawalKey,
value: Withdrawal,
}) {}

@runtimeModule()
export class Withdrawals extends RuntimeModule {
@state() withdrawalCounter = State.from(Field);
events = new RuntimeEvents({
withdrawal: WithdrawalEvent,
});

@state() withdrawalCounters = StateMap.from(Field, Field);

@state() withdrawals = StateMap.from<Field, Withdrawal>(Field, Withdrawal);
@state() withdrawals = StateMap.from<WithdrawalKey, Withdrawal>(
WithdrawalKey,
Withdrawal
);

public constructor(@inject("Balances") private readonly balances: Balances) {
super();
}

protected async queueWithdrawal(withdrawal: Withdrawal) {
const counter = (await this.withdrawalCounter.get()).orElse(Field(0));
const { tokenId } = withdrawal;
const counter = (await this.withdrawalCounters.get(tokenId)).orElse(
Field(0)
);

const key = { index: counter, tokenId };
await this.withdrawals.set(key, withdrawal);

await this.withdrawals.set(counter, withdrawal);
await this.withdrawalCounters.set(tokenId, counter.add(1));

await this.withdrawalCounter.set(counter.add(1));
this.events.emit("withdrawal", {
key,
value: withdrawal,
});
}

public async withdraw(address: PublicKey, amount: UInt64) {
const balance = await this.balances.getBalance(TokenId.from(0), address);
public async withdraw(address: PublicKey, amount: UInt64, tokenId: Field) {
const balance = await this.balances.getBalance(tokenId, address);

const accountCreationFee = UInt64.Unsafe.fromField(Field(1n).mul(1e9));
amount.assertGreaterThanOrEqual(
Expand All @@ -36,18 +67,15 @@ export class Withdrawals extends RuntimeModule {
balance.assertGreaterThanOrEqual(amount, "Not enough balance");

// Deduct balance from user
await this.balances.setBalance(
TokenId.from(0),
address,
balance.sub(amount)
);
await this.balances.setBalance(tokenId, address, balance.sub(amount));

// Add withdrawal to queue
await this.queueWithdrawal(
new Withdrawal({
address,
// Has to be o1js UInt since the withdrawal will be processed in a o1js SmartContract
amount: amount.toO1UInt64(),
tokenId: tokenId,
})
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/module/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"peerDependencies": {
"@proto-kit/common": "*",
"@proto-kit/protocol": "*",
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"tsyringe": "^4.7.0"
},
"gitHead": "397881ed5d8f98f5005bcd7be7f5a12b3bc6f956"
Expand Down
2 changes: 1 addition & 1 deletion packages/persistance/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"@proto-kit/module": "*",
"@proto-kit/protocol": "*",
"@proto-kit/sequencer": "*",
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"tsyringe": "^4.7.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/protocol/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
},
"peerDependencies": {
"@proto-kit/common": "*",
"o1js": "^1.1.0",
"o1js": "^1.6.0",
"ts-pattern": "^4.3.0",
"tsyringe": "^4.7.0"
},
Expand Down
6 changes: 6 additions & 0 deletions packages/protocol/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,16 @@ export * from "./state/StateMap";
export * from "./state/StateService";
export * from "./state/StateServiceProvider";
export * from "./state/assert/assert";
export * from "./settlement/contracts/authorizations/ContractAuthorization";
export * from "./settlement/contracts/authorizations/UpdateMessagesHashAuth";
export * from "./settlement/contracts/authorizations/TokenBridgeDeploymentAuth";
export * from "./settlement/contracts/SettlementSmartContract";
export * from "./settlement/contracts/SettlementContractProtocolModule";
export * from "./settlement/contracts/DispatchSmartContract";
export * from "./settlement/contracts/DispatchContractProtocolModule";
export * from "./settlement/contracts/BridgeContract";
export * from "./settlement/contracts/BridgeContractProtocolModule";
export * from "./settlement/contracts/TokenBridgeTree";
export * from "./settlement/SettlementContractModule";
export * from "./settlement/ContractModule";
export * from "./settlement/modularity/ProvableSettlementHook";
Expand Down
15 changes: 9 additions & 6 deletions packages/protocol/src/settlement/ContractModule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ConfigurableModule, NoConfig, TypedClass } from "@proto-kit/common";
import {
CompileArtifact,
ConfigurableModule,
NoConfig,
TypedClass,
} from "@proto-kit/common";
import { SmartContract } from "o1js";

export type SmartContractClassFromInterface<Type> = typeof SmartContract &
Expand All @@ -14,11 +19,9 @@ export type SmartContractClassFromInterface<Type> = typeof SmartContract &
*/
export abstract class ContractModule<
ContractType,
// undefined = no args
Arguments = undefined,
Config = NoConfig,
> extends ConfigurableModule<Config> {
public abstract contractFactory(
args: Arguments
): SmartContractClassFromInterface<ContractType>;
public abstract contractFactory(): SmartContractClassFromInterface<ContractType>;

public abstract compile(): Promise<Record<string, CompileArtifact>>;
}
Loading
Loading