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

Consider integrating features used by wallet's into the repo #784

Open
tabaktoni opened this issue Oct 13, 2023 · 13 comments
Open

Consider integrating features used by wallet's into the repo #784

tabaktoni opened this issue Oct 13, 2023 · 13 comments
Labels
Type: feature New feature or request

Comments

@tabaktoni
Copy link
Collaborator

Reported by Axel
please consider including some of this code in starknet.js as we end up redefining it in all of our projects

import {
  CallData,
  Contract,
  hash,
  Signer,
  encode,
  ec,
  type RawArgs,
  SignerInterface,
  type Signature,
  typedData,
  transaction,
  type Abi,
  type Call,
  type DeclareSignerDetails,
  type DeployAccountSignerDetails,
  type InvocationsSignerDetails,
} from "starknet";
import { SequencerProvider } from "starknet";

const devnetBaseUrl = "http://127.0.0.1:5050";

export const provider = new SequencerProvider({ baseUrl: devnetBaseUrl });

export async function loadContract(contractAddress: string) {
  const { abi } = await provider.getClassAt(contractAddress);
  if (!abi) {
    throw new Error("Error while getting ABI");
  }
  return new Contract(abi, contractAddress, provider);
}

export class KeyPair extends Signer {
  constructor(pk?: string | bigint) {
    super(pk ? `${pk}` : `0x${encode.buf2hex(ec.starkCurve.utils.randomPrivateKey())}`);
  }

  public get privateKey() {
    return BigInt(this.pk as string);
  }

  public get publicKey() {
    return BigInt(ec.starkCurve.getStarkKey(this.pk));
  }

  public signHash(messageHash: string) {
    const { r, s } = ec.starkCurve.sign(messageHash, this.pk);
    return [r.toString(), s.toString()];
  }
}

export const randomKeyPair = () => new KeyPair();

/**
 * This class allows to easily implement custom signers by overriding the `signRaw` method.
 * This is based on Starknet.js implementation of Signer, but it delegates the actual signing to an abstract function
 */
export abstract class RawSigner implements SignerInterface {
  abstract signRaw(messageHash: string): Promise<Signature>;

  public async getPubKey(): Promise<string> {
    throw Error("This signer allows multiple public keys");
  }

  public async signMessage(typedDataArgument: typedData.TypedData, accountAddress: string): Promise<Signature> {
    const messageHash = typedData.getMessageHash(typedDataArgument, accountAddress);
    return this.signRaw(messageHash);
  }

  public async signTransaction(
    transactions: Call[],
    transactionsDetail: InvocationsSignerDetails,
    abis?: Abi[],
  ): Promise<Signature> {
    if (abis && abis.length !== transactions.length) {
      throw new Error("ABI must be provided for each transaction or no transaction");
    }
    // now use abi to display decoded data somewhere, but as this signer is headless, we can't do that
    const calldata = transaction.getExecuteCalldata(transactions, transactionsDetail.cairoVersion);

    const messageHash = hash.calculateTransactionHash(
      transactionsDetail.walletAddress,
      transactionsDetail.version,
      calldata,
      transactionsDetail.maxFee,
      transactionsDetail.chainId,
      transactionsDetail.nonce,
    );
    return this.signRaw(messageHash);
  }

  public async signDeployAccountTransaction({
    classHash,
    contractAddress,
    constructorCalldata,
    addressSalt,
    maxFee,
    version,
    chainId,
    nonce,
  }: DeployAccountSignerDetails) {
    const messageHash = hash.calculateDeployAccountTransactionHash(
      contractAddress,
      classHash,
      CallData.compile(constructorCalldata),
      addressSalt,
      version,
      maxFee,
      chainId,
      nonce,
    );

    return this.signRaw(messageHash);
  }

  public async signDeclareTransaction(
    // contractClass: ContractClass,  // Should be used once class hash is present in ContractClass
    { classHash, senderAddress, chainId, maxFee, version, nonce, compiledClassHash }: DeclareSignerDetails,
  ) {
    const messageHash = hash.calculateDeclareTransactionHash(
      classHash,
      senderAddress,
      version,
      maxFee,
      chainId,
      nonce,
      compiledClassHash,
    );

    return this.signRaw(messageHash);
  }
}

export async function mintEth(address: string) {
  await handlePost("mint", { address, amount: 1e18, lite: true });
}

async function handlePost(path: string, payload?: RawArgs) {
  const response = await fetch(`${provider.baseUrl}/${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status} Message: ${await response.text()}`);
  }
}
@tabaktoni tabaktoni added the Type: feature New feature or request label Oct 13, 2023
@tabaktoni tabaktoni added the OnlyDust Open for OnlyDust contributors label Oct 27, 2023
@edisontim
Copy link
Contributor

Hello! Can I take this?

@ivpavici
Copy link
Collaborator

@edisontim sure! thanks!

@edisontim
Copy link
Contributor

edisontim commented Nov 27, 2023

Do you know where I can find any RawSigner actual implementation that I could use to test this with?

@WiseMrMusa
Copy link

@edisontim how far, are you still working on this?

@edisontim
Copy link
Contributor

edisontim commented Feb 26, 2024

Hey! I have a branch with everything implemented but needed a RawSigner implementation to test it. I left the issue on the side for a while but just sent a message to Alex from Argent to get it. Will start working on it again when I get an answer :)

@WiseMrMusa
Copy link

Hi! Are you still working on it?

@edisontim
Copy link
Contributor

Hey! No you can take this :)

@ivpavici ivpavici assigned WiseMrMusa and unassigned edisontim Mar 26, 2024
@ivpavici
Copy link
Collaborator

@WiseMrMusa good luck! :)

@WiseMrMusa
Copy link

I am just seeing this now, I will add it to my schedule 😄

@ivpavici
Copy link
Collaborator

unassigned due to being stale and will be offered to participants of the ODHack event
https://onlydust.notion.site/ODHack-Common-Guidelines-b9c6b6a4ac4146d087185568aca38a3f

@ivpavici ivpavici added the ODHack Issue to assign for the ODHack event label Apr 19, 2024
@IjayAbby
Copy link

Hello @ivpavici can I work on this?

@IjayAbby
Copy link

@ivpavici what are some of the methods that I need to implement?

@ivpavici
Copy link
Collaborator

@tabaktoni can you please point out a bit more details?

@ivpavici ivpavici removed the ODHack Issue to assign for the ODHack event label Jul 15, 2024
@ivpavici ivpavici removed the OnlyDust Open for OnlyDust contributors label Sep 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: feature New feature or request
Projects
Status: No status
Development

No branches or pull requests

5 participants