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

Attempt MultiSign #143

Draft
wants to merge 7 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();
36 changes: 27 additions & 9 deletions src/chains/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export class NearEthAdapter {
readonly mpcContract: IMpcContract;
readonly address: Address;
readonly derivationPath: string;
readonly keyVersion: number;
readonly beta: Beta;

private constructor(config: {
Expand All @@ -41,6 +42,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 @@ -103,16 +105,33 @@ export class NearEthAdapter {
* Note that the signature request is a recursive function.
*/
async signAndSendTransaction(
txData: BaseTx,
txData: BaseTx[],
nearGas?: bigint
): Promise<Hash> {
const { transaction, signArgs } = await this.createTxPayload(txData);
): 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 signature = await this.mpcContract.requestSignature(
signArgs,
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 @@ -170,11 +189,10 @@ export class NearEthAdapter {
* @returns Transaction and its bytes (the payload to be signed on Near).
*/
async createTxPayload(tx: BaseTx): Promise<TxPayload> {
const transaction = await this.buildTransaction(tx);
console.log(
`Creating payload for sender: ${this.nearAccountId()} <> ${this.address}`
`Built (unsigned) Transaction for chainId=${tx.chainId}: ${transaction}`
);
const transaction = await this.buildTransaction(tx);
console.log("Built (unsigned) Transaction", transaction);
const signArgs = {
payload: buildTxPayload(transaction),
path: this.derivationPath,
Expand Down
45 changes: 43 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 @@ -117,7 +117,17 @@ export class MpcContract implements IMpcContract {
// });
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);
};

async encodeSignatureRequestTx(
Expand All @@ -141,6 +151,32 @@ export class MpcContract implements IMpcContract {
};
}

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,
},
};
}),
};
}

async signAndSendSignRequest(
transaction: FunctionCallTransaction<{ request: SignArgs }>,
blockTimeout: number = 30
Expand Down Expand Up @@ -191,8 +227,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 @@ -48,6 +48,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.");
}

accountId(): string {
return "mock-mpc.offline";
Expand Down
98 changes: 64 additions & 34 deletions src/utils/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ export interface JSONRPCResponse<T> {
};
}

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 @@ -50,9 +50,8 @@ export async function signatureFromTxHash(
if (json.error) {
throw new Error(`JSON-RPC error: ${json.error.message}`);
}

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

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

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}`);
// }
}

// type guard for MPCSignature object.
Expand Down
42 changes: 24 additions & 18 deletions tests/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,28 @@ describe("End To End", () => {

it.skip("signAndSendTransaction", async () => {
await expect(
realAdapter.signAndSendTransaction({
// Sending 1 WEI to self (so we never run out of funds)
to: realAdapter.address,
value: ONE_WEI,
chainId,
})
realAdapter.signAndSendTransaction([
{
// Sending 1 WEI to self (so we never run out of funds)
to: realAdapter.address,
value: ONE_WEI,
chainId,
},
])
).resolves.not.toThrow();
});

it.skip("signAndSendTransaction - Gnosis Chain", async () => {
await expect(
realAdapter.signAndSendTransaction({
// Sending 1 WEI to self (so we ~never run out of funds)
to: realAdapter.address,
value: ONE_WEI,
// Gnosis Chain!
chainId: 100,
})
realAdapter.signAndSendTransaction([
{
// Sending 1 WEI to self (so we ~never run out of funds)
to: realAdapter.address,
value: ONE_WEI,
// Gnosis Chain!
chainId: 100,
},
])
).resolves.not.toThrow();
});

Expand All @@ -54,11 +58,13 @@ describe("End To End", () => {
address: mockedAdapter.address,
});
await expect(
mockedAdapter.signAndSendTransaction({
to,
value: senderBalance + ONE_WEI,
chainId,
})
mockedAdapter.signAndSendTransaction([
{
to,
value: senderBalance + ONE_WEI,
chainId,
},
])
).rejects.toThrow();
}, 15000);

Expand Down
Loading
Loading