Skip to content
New issue

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

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

Already on GitHub? # to your account

Attempt MultiSign #143

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
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
16 changes: 8 additions & 8 deletions examples/send-eth.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import dotenv from "dotenv";
import { SEPOLIA_CHAIN_ID, setupNearEthAdapter } from "./setup";
import { setupNearEthAdapter } from "./setup";
dotenv.config();

const run = async (): Promise<void> => {
const evm = await setupNearEthAdapter();
await evm.signAndSendTransaction({
// Sending to self.
to: evm.address,
// THIS IS ONE WEI!
value: 1n,
chainId: SEPOLIA_CHAIN_ID,
});
const { to, value } = { to: evm.address, value: 1n };
// MULTI-SEND!
const transactions = [
{ to, value, chainId: 11155111 },
{ to, value, chainId: 1301 },
];
await evm.signAndSendTransaction(transactions);
};

run();
37 changes: 30 additions & 7 deletions src/chains/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export class NearEthAdapter {
readonly mpcContract: IMpcContract;
readonly address: Address;
readonly derivationPath: string;
readonly keyVersion: number;
readonly beta: Beta;

private constructor(config: {
Expand All @@ -45,6 +46,7 @@ export class NearEthAdapter {
}) {
this.mpcContract = config.mpcContract;
this.derivationPath = config.derivationPath;
this.keyVersion = 0;
this.address = config.sender;
this.beta = new Beta(this);
}
Expand Down Expand Up @@ -117,18 +119,36 @@ export class NearEthAdapter {
*
* @param txData - Minimal transaction data to be signed by Near MPC and executed on EVM
* @param nearGas - Manually specified gas to be sent with signature request
* @returns The ethereum transaction hash
* @returns The ethereum transaction hashes aligned with txData indices.
*/
async signAndSendTransaction(
txData: BaseTx,
txData: BaseTx[],
nearGas?: bigint
): Promise<Hash> {
const { transaction, signArgs } = await this.createTxPayload(txData);
const signature = await this.mpcContract.requestSignature(
signArgs,
): Promise<Hash[]> {
// TODO: Note that chainIds must be all different or
// we will have to make special consideration for the nonces.
console.log(
`Creating ${txData.length} payload(s) for ${this.nearAccountId()} <> ${this.address}`
);

const txArray = await Promise.all(
txData.map((tx) => this.createTxPayload(tx))
);

console.log(`Requesting signature from ${this.mpcContract.accountId()}`);
const signatures = await this.mpcContract.requestMulti(
txArray.map((tx) => tx.signArgs),
nearGas
);
return broadcastSignedTransaction({ transaction, signature });
const transactions = txArray.map((tx) => tx.transaction);
return Promise.all(
transactions.map((transaction, i) =>
broadcastSignedTransaction({
transaction,
signature: signatures[i]!,
})
)
);
}

/**
Expand Down Expand Up @@ -187,6 +207,9 @@ export class NearEthAdapter {
*/
async createTxPayload(tx: BaseTx): Promise<TxPayload> {
const transaction = await this.buildTransaction(tx);
console.log(
`Built (unsigned) Transaction for chainId=${tx.chainId}: ${transaction}`
);
const signArgs = {
payload: buildTxPayload(transaction),
path: this.derivationPath,
Expand Down
52 changes: 50 additions & 2 deletions src/mpcContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from "./utils/kdf";
import { TGAS } from "./chains/near";
import { MPCSignature, FunctionCallTransaction, SignArgs } from "./types";
import { signatureFromOutcome } from "./utils/signature";
import { signaturesFromOutcome } from "./utils/signature";
import { FinalExecutionOutcome } from "near-api-js/lib/providers";

/**
Expand Down Expand Up @@ -119,7 +119,17 @@ export class MpcContract implements IMpcContract {
): Promise<Signature> => {
const transaction = await this.encodeSignatureRequestTx(signArgs, gas);
const outcome = await this.signAndSendSignRequest(transaction);
return signatureFromOutcome(outcome);
// signaturesFromOutcome guarantees non empty array > 0.
return signaturesFromOutcome(outcome)[0]!;
};

requestMulti = async (
signArgs: SignArgs[],
gas?: bigint
): Promise<Signature[]> => {
const transaction = await this.encodeMulti(signArgs, gas);
const result = await this.signAndSendSignRequest(transaction);
return signaturesFromOutcome(result);
};

/**
Expand Down Expand Up @@ -150,6 +160,39 @@ export class MpcContract implements IMpcContract {
};
}

/**
* Encodes multiple signature requests into a single transaction.
*
* @param signArgs - The array of arguments for the signature requests
* @param gas - Optional gas limit
* @returns The encoded transaction
*/
async encodeMulti(
signArgs: SignArgs[],
gas?: bigint
): Promise<FunctionCallTransaction<{ request: SignArgs }>> {
const deposit = await this.getDeposit();
// TODO: This is a hack to prevent out of gas errors
const maxGasPerAction = (gas || 300000000000000n) / BigInt(signArgs.length);
return {
signerId: this.connectedAccount.accountId,
receiverId: this.contract.contractId,
actions: signArgs.map((args) => {
return {
type: "FunctionCall",
params: {
methodName: "sign",
args: {
request: args,
},
gas: maxGasPerAction.toString(),
deposit,
},
};
}),
};
}

/**
* Signs and sends a signature request
*
Expand Down Expand Up @@ -210,8 +253,13 @@ export interface IMpcContract {
deriveEthAddress(derivationPath: string): Promise<Address>;
getDeposit(): Promise<string>;
requestSignature(signArgs: SignArgs, gas?: bigint): Promise<Signature>;
requestMulti(signArgs: SignArgs[], gas?: bigint): Promise<Signature[]>;
encodeSignatureRequestTx(
signArgs: SignArgs,
gas?: bigint
): Promise<FunctionCallTransaction<{ request: SignArgs }>>;
encodeMulti(
signArgs: SignArgs[],
gas?: bigint
): Promise<FunctionCallTransaction<{ request: SignArgs }>>;
}
9 changes: 9 additions & 0 deletions src/utils/mock-sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ export class MockMpcContract implements IMpcContract {
"0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
);
}
requestMulti(_signArgs: SignArgs[], _gas?: bigint): Promise<Signature[]> {
throw new Error("Method not implemented.");
}
encodeMulti(
_signArgs: SignArgs[],
_gas?: bigint
): Promise<FunctionCallTransaction<{ request: SignArgs }>> {
throw new Error("Method not implemented.");
}

/** Gets the mock contract ID */
accountId(): string {
Expand Down
98 changes: 65 additions & 33 deletions src/utils/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ export interface JSONRPCResponse<T> {
* @returns The signature from the transaction
* @throws Error if HTTP request fails or response is invalid
*/
export async function signatureFromTxHash(
export async function signaturesFromTxHash(
nodeUrl: string,
txHash: string,
/// This field doesn't appear to be necessary although (possibly for efficiency),
/// the docs mention that it is "used to determine which shard to query for transaction".
accountId: string = "non-empty"
): Promise<Signature> {
): Promise<Signature[]> {
const payload = {
jsonrpc: "2.0",
id: "dontcare",
Expand All @@ -65,6 +65,7 @@ export async function signatureFromTxHash(
if (json.error) {
throw new Error(`JSON-RPC error: ${json.error.message}`);
}

if (
typeof json.result?.status === "object" &&
"Failure" in json.result.status
Expand All @@ -76,7 +77,7 @@ export async function signatureFromTxHash(
}

if (json.result) {
return signatureFromOutcome(json.result);
return signaturesFromOutcome(json.result);
} else {
throw new Error(`No FinalExecutionOutcome in response: ${json}`);
}
Expand All @@ -97,6 +98,10 @@ export function transformSignature(mpcSig: MPCSignature): Signature {
};
}

function isNonEmptyString(value: unknown): value is string {
return typeof value === "string" && value.trim().length > 0;
}

/**
* Extracts a signature from a transaction outcome
*
Expand All @@ -108,47 +113,74 @@ export function transformSignature(mpcSig: MPCSignature): Signature {
* extracts signature from receipts_outcome, taking the second occurrence as
* the first is nested inside `{ Ok: MPCSignature }`.
*/
export function signatureFromOutcome(
export function signaturesFromOutcome(
// The Partial object is intended to make up for the
// difference between all the different near-api versions and wallet-selector bullshit
// the field `final_execution_status` is in one, but not the other and we don't use it anyway.
outcome:
| FinalExecutionOutcome
| Omit<FinalExecutionOutcome, "final_execution_status">
): Signature {
): Signature[] {
const successValues: string[] = outcome.receipts_outcome
// Map to get SuccessValues: The Signature will appear twice.
.map(
(receipt) => (receipt.outcome.status as FinalExecutionStatus).SuccessValue
)
.filter((b64) => isNonEmptyString(b64));

const signatures = successValues
.map((v) => {
const decodedValue = Buffer.from(v, "base64").toString("utf-8");
const possibleSignature = JSON.parse(decodedValue);
if (isMPCSignature(possibleSignature)) {
return transformSignature(possibleSignature);
}
return;
})
.filter((sig) => sig !== undefined);

const txHash = outcome.transaction_outcome?.id;
// TODO - find a scenario when outcome.status is `FinalExecutionStatusBasic`!
let b64Sig = (outcome.status as FinalExecutionStatus).SuccessValue;
if (!b64Sig) {
// This scenario occurs when sign call is relayed (i.e. executed by someone else).
// E.g. https://testnet.nearblocks.io/txns/G1f1HVUxDBWXAEimgNWobQ9yCx1EgA2tzYHJBFUfo3dj
// We have to dig into `receipts_outcome` and extract the signature from within.
// We want the second occurence of the signature because
// the first is nested inside `{ Ok: MPCSignature }`)
b64Sig = outcome.receipts_outcome
// Map to get SuccessValues: The Signature will appear twice.
.map(
(receipt) =>
(receipt.outcome.status as FinalExecutionStatus).SuccessValue
)
// Reverse the to "find" the last non-empty value!
.reverse()
.find((value) => value && value.trim().length > 0);
}
if (!b64Sig) {
throw new Error(`No detectable signature found in transaction ${txHash}`);
}
if (b64Sig === "eyJFcnIiOiJGYWlsZWQifQ==") {
if (successValues.includes("eyJFcnIiOiJGYWlsZWQifQ==")) {
// {"Err": "Failed"}
throw new Error(`Signature Request Failed in ${txHash}`);
}
const decodedValue = Buffer.from(b64Sig, "base64").toString("utf-8");
const signature = JSON.parse(decodedValue);
if (isMPCSignature(signature)) {
return transformSignature(signature);
} else {
throw new Error(`No detectable signature found in transaction ${txHash}`);
if (signatures.length === 0) {
throw new Error(`No signature detected in transaction ${txHash}`);
}
return signatures;

// // TODO - find a scenario when outcome.status is `FinalExecutionStatusBasic`!
// let b64Sig = (outcome.status as FinalExecutionStatus).SuccessValue;
// if (!b64Sig) {
// // This scenario occurs when sign call is relayed (i.e. executed by someone else).
// // E.g. https://testnet.nearblocks.io/txns/G1f1HVUxDBWXAEimgNWobQ9yCx1EgA2tzYHJBFUfo3dj
// // We have to dig into `receipts_outcome` and extract the signature from within.
// // We want the second occurence of the signature because
// // the first is nested inside `{ Ok: MPCSignature }`)
// b64Sig = outcome.receipts_outcome
// // Map to get SuccessValues: The Signature will appear twice.
// .map(
// (receipt) =>
// (receipt.outcome.status as FinalExecutionStatus).SuccessValue
// )
// // Reverse the to "find" the last non-empty value!
// .reverse()
// .find((value) => value && value.trim().length > 0);
// }
// if (!b64Sig) {
// throw new Error(`No detectable signature found in transaction ${txHash}`);
// }
// if (b64Sig === "eyJFcnIiOiJGYWlsZWQifQ==") {
// // {"Err": "Failed"}
// throw new Error(`Signature Request Failed in ${txHash}`);
// }
// const decodedValue = Buffer.from(b64Sig, "base64").toString("utf-8");
// const signature = JSON.parse(decodedValue);
// if (isMPCSignature(signature)) {
// return transformSignature(signature);
// } else {
// throw new Error(`No detectable signature found in transaction ${txHash}`);
// }
}

/**
Expand Down
Loading
Loading