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

Viem wip #3

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
939 changes: 939 additions & 0 deletions packages/client/abi/EssentialForwarder.ts

Large diffs are not rendered by default.

52 changes: 52 additions & 0 deletions packages/client/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {
Account,
Address,
ParseAccount,
Transport,
WalletClient,
WalletClientConfig,
createClient,
walletActions,
} from "viem";
import { Chain } from "viem/chains";
import {
CustomSendTransactionParameters,
sendTransaction,
} from "./sendTransaction";

export function createEssentialClient<
TTransport extends Transport,
TChain extends Chain | undefined = undefined,
TAccountOrAddress extends Account | Address | undefined = undefined
>({
account,
chain,
transport,
key = "wallet",
name = "Essential Client",
pollingInterval,
}: WalletClientConfig<TTransport, TChain, TAccountOrAddress>): WalletClient<
TTransport,
TChain,
ParseAccount<TAccountOrAddress>
> {
const client = createClient({
account,
chain,
key,
name,
pollingInterval,
transport: (opts) => transport({ ...opts, retryCount: 0 }),
type: "walletClient",
}).extend((client) => ({
...walletActions(client),
sendTransaction: (args: CustomSendTransactionParameters) =>
sendTransaction(client, args),
}));

return client as WalletClient<
TTransport,
TChain,
ParseAccount<TAccountOrAddress>
>;
}
65 changes: 65 additions & 0 deletions packages/client/messageBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Contract } from "@ethersproject/contracts";

import { BigNumber, BigNumberish, BytesLike } from "ethers";

import {
EssentialForwarder,
IForwardRequest,
} from "./typechain/contracts/fwd/EssentialForwarder.js";

export interface ForwardRequestInput {
to: string;
from: string;
authorizer: string;
nftContract: string;
nftChainId: BigNumberish;
nftTokenId: BigNumberish;
targetChainId: BigNumberish;
data: BytesLike;
nonce?: BigNumberish;
}

export async function getNonce(
forwarder: Contract,
from: string
): Promise<BigNumber> {
const nonce = await forwarder.getNonce(from);

return nonce;
}

async function attachNonce(
forwarder: Contract,
input: Record<string, any>
): Promise<IForwardRequest.ERC721ForwardRequestStruct> {
const nonce = await getNonce(forwarder, input.from).then((nonce: BigNumber) =>
nonce.toString()
);

return {
value: BigNumber.from(0),
gas: 1e6,
to: input.to,
from: input.from,
authorizer: input.authorizer,
nftContract: input.nftContract,
nonce,
nftChainId: input.nftChainId,
nftTokenId: input.nftTokenId,
targetChainId: input.targetChainId,
data: input.data,
};
}

export async function prepareRequest(
input: ForwardRequestInput,
forwarder: EssentialForwarder | Contract
): Promise<{
request: IForwardRequest.ERC721ForwardRequestStruct;
}> {
const request = await attachNonce(forwarder, input);

return {
request,
};
}
203 changes: 203 additions & 0 deletions packages/client/messageSigner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { Provider as AbstractProvider } from '@ethersproject/abstract-provider';
import { Contract } from '@ethersproject/contracts';
import { Provider, Web3Provider } from '@ethersproject/providers';
import {
signTypedData as signWithKey,
SignTypedDataVersion,
TypedMessage,
} from '@metamask/eth-sig-util';
import { BigNumber, BigNumberish, BytesLike, utils } from 'ethers';

import {
EssentialForwarder,
IForwardRequest,
} from '../typechain/contracts/fwd/EssentialForwarder.js';

/**
* Field in a User Defined Types
*/
export interface EIP712StructField {
name: string;
type: string;
}

/**
* User Defined Types are just an array of the fields they contain
*/
export type EIP712Struct = EIP712StructField[];
/**
* Interface of the EIP712Domain structure
*/
export interface EIP712Domain {
name: string;
version: string;
chainId?: number;
verifyingContract: string;
salt?: string;
}

/**
* Interface of the complete payload required for signing
*/
export interface EIP712Payload {
types: PayloadTypes;
primaryType: string;
message: IForwardRequest.ERC721ForwardRequestStruct;
domain: EIP712Domain;
}

export interface EIP712Signature {
hex: string;
v: number;
s: string;
r: string;
}

const EIP712Domain = [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'verifyingContract', type: 'address' },
{ name: 'salt', type: 'bytes32' },
];

const ForwardRequest = [
{ name: 'to', type: 'address' },
{ name: 'from', type: 'address' },
{ name: 'authorizer', type: 'address' },
{ name: 'nftContract', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'nftChainId', type: 'uint256' },
{ name: 'nftTokenId', type: 'uint256' },
{ name: 'targetChainId', type: 'uint256' },
{ name: 'data', type: 'bytes' },
];

export interface ForwardRequestInput {
to: string;
from: string;
authorizer: string;
nftContract: string;
nftChainId: BigNumberish;
nftTokenId: BigNumberish;
targetChainId: BigNumberish;
data: BytesLike;
nonce?: BigNumberish;
}

const MinimalRequest = [
{ name: 'to', type: 'address' },
{ name: 'from', type: 'address' },
{ name: 'authorizer', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'targetChainId', type: 'uint256' },
{ name: 'data', type: 'bytes' },
];

interface PayloadTypes {
EIP712Domain: EIP712Struct;
ForwardRequest: EIP712Struct;
MinimalRequest: EIP712Struct;
}

function getMetaTxTypeData(
verifyingContract: string,
_chainId: number,
message: IForwardRequest.ERC721ForwardRequestStruct,
name: string,
primaryType: string,
): EIP712Payload {
return {
types: {
EIP712Domain,
ForwardRequest,
MinimalRequest,
},
domain: {
name,
version: '0.0.1',
verifyingContract,
salt: utils.hexZeroPad(BigNumber.from(_chainId).toHexString(), 32),
},
primaryType,
message,
};
}

async function signTypedData(
signer: string | Web3Provider,
from: string,
data: EIP712Payload,
) {
// If signer is a private key, use it to sign
if (typeof signer === 'string') {
const privateKey = Buffer.from(signer.replace(/^0x/, ''), 'hex');
return signWithKey({
privateKey,
data: data as unknown as TypedMessage<any>,
version: SignTypedDataVersion.V3,
});
}

return await signer.send('eth_signTypedData_v4', [
from,
JSON.stringify(data),
]);
}

async function attachNonce(
forwarder: Contract,
input: Record<string, any>,
): Promise<IForwardRequest.ERC721ForwardRequestStruct> {

const nonce =
input?.nonce ||
(await forwarder
.getNonce(input.from)
.then((nonce: BigNumber) => nonce.toString()));

return {
value: BigNumber.from(0),
gas: 1e6,
to: input.to,
from: input.from,
authorizer: input.authorizer,
nftContract: input.nftContract,
nonce,
nftChainId: input.nftChainId,
nftTokenId: input.nftTokenId,
targetChainId: input.targetChainId,
data: input.data,
};
}

export async function signMetaTxRequest(
signer: string | Provider | AbstractProvider,
input: ForwardRequestInput,
forwarder: EssentialForwarder | Contract,
domainName?: string,
): Promise<{
signature: string;
request: IForwardRequest.ERC721ForwardRequestStruct;
}> {
const chainId = await forwarder.getChainId();
const request = await attachNonce(forwarder, input);

const toSign = getMetaTxTypeData(
forwarder.address,
chainId,
request,
domainName || '0xEssential PlaySession',
request.nftContract ? 'ForwardRequest' : 'MinimalRequest',
);

const signature = await signTypedData(
signer as Web3Provider,
input.from,
toSign,
);

return {
signature,
request,
};
}
61 changes: 61 additions & 0 deletions packages/client/offchainLookup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Contract, ethers } from 'ethers';

import { abi } from '../abi/EssentialForwarder.js';

async function retrieveProof({
url,
callData,
forwarder,
}: {
url: string;
callData: string;
forwarder: {
address: string;
abi: any;
};
}): Promise<string> {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'durin_call',
params: { callData, to: forwarder.address, abi: forwarder.abi },
}),
});

const body = await response.json();

return body?.result;
}

export const handleOffchainLookup = async (
args: {
callData: string;
callbackFunction: string;
extraData: string;
urls: string[];
},
forwarder: Contract,
): Promise<string> => {
const { callData, callbackFunction, extraData, urls } = args;

const abiCoder = new ethers.utils.AbiCoder();

// hit OwnershipAPI for proof
const proof = await retrieveProof({
url: urls[0],
callData,
forwarder: { address: forwarder.address, abi },
});

return ethers.utils.hexConcat([
callbackFunction,
abiCoder.encode(['bytes', 'bytes'], [proof, extraData]),
]);

// const tx = await forwarder.signer.sendTransaction({
// to: forwarder.address,
// data: __return_value___
// });
};
Loading