diff --git a/src/account/index.ts b/src/account/index.ts index 4a61b9d06..3435780bb 100644 --- a/src/account/index.ts +++ b/src/account/index.ts @@ -1,2 +1,3 @@ export * from './default'; export * from './interface'; +export * from './session'; diff --git a/src/account/session.ts b/src/account/session.ts new file mode 100644 index 000000000..09e22be0e --- /dev/null +++ b/src/account/session.ts @@ -0,0 +1,141 @@ +import { ZERO } from '../constants'; +import { ProviderInterface, ProviderOptions } from '../provider'; +import { SignerInterface } from '../signer'; +import { + Abi, + Call, + EstimateFee, + EstimateFeeDetails, + InvocationsDetails, + InvocationsSignerDetails, + InvokeFunctionResponse, + KeyPair, +} from '../types'; +import { feeTransactionVersion, transactionVersion } from '../utils/hash'; +import { BigNumberish, toBN } from '../utils/number'; +import type { SignedSession } from '../utils/session'; +import { compileCalldata, estimatedFeeToMaxFee } from '../utils/stark'; +import { fromCallsToExecuteCalldataWithNonce } from '../utils/transaction'; +import { Account } from './default'; +import { AccountInterface } from './interface'; + +const SESSION_PLUGIN_CLASS_HASH = + '0x6a184757e350de1fe3a544037efbef6434724980a572f294c90555dadc20052'; + +export class SessionAccount extends Account implements AccountInterface { + constructor( + providerOrOptions: ProviderOptions | ProviderInterface, + address: string, + keyPairOrSigner: KeyPair | SignerInterface, + public signedSession: SignedSession + ) { + super(providerOrOptions, address, keyPairOrSigner); + } + + private async sessionToCall(session: SignedSession): Promise { + return { + contractAddress: this.address, + entrypoint: 'use_plugin', + calldata: compileCalldata({ + SESSION_PLUGIN_CLASS_HASH, + signer: await this.signer.getPubKey(), + expires: session.expires.toString(), + token1: session.signature[0], + token2: session.signature[1], + root: session.root, + proof: [], + }), + }; + } + + private async extendCallsBySession(calls: Call[], session: SignedSession): Promise { + return [await this.sessionToCall(session), ...calls]; + } + + public async estimateFee( + calls: Call | Call[], + { nonce: providedNonce, blockIdentifier }: EstimateFeeDetails = {} + ): Promise { + const transactions = await this.extendCallsBySession( + Array.isArray(calls) ? calls : [calls], + this.signedSession + ); + const nonce = providedNonce ?? (await this.getNonce()); + const version = toBN(feeTransactionVersion); + + const signerDetails: InvocationsSignerDetails = { + walletAddress: this.address, + nonce: toBN(nonce), + maxFee: ZERO, + version, + chainId: this.chainId, + }; + + const signature = await this.signer.signTransaction(transactions, signerDetails); + + const calldata = fromCallsToExecuteCalldataWithNonce(transactions, nonce); + const response = await super.getEstimateFee( + { contractAddress: this.address, entrypoint: '__execute__', calldata, signature }, + blockIdentifier, + { version } + ); + + const suggestedMaxFee = estimatedFeeToMaxFee(response.overall_fee); + + return { + ...response, + suggestedMaxFee, + }; + } + + /** + * Invoke execute function in account contract + * + * [Reference](https://github.com/starkware-libs/cairo-lang/blob/f464ec4797361b6be8989e36e02ec690e74ef285/src/starkware/starknet/services/api/gateway/gateway_client.py#L13-L17) + * + * @param calls - one or more calls to be executed + * @param abis - one or more abis which can be used to display the calls + * @param transactionsDetail - optional transaction details + * @returns a confirmation of invoking a function on the starknet contract + */ + public async execute( + calls: Call | Call[], + abis: Abi[] | undefined = undefined, + transactionsDetail: InvocationsDetails = {} + ): Promise { + const transactions = await this.extendCallsBySession( + Array.isArray(calls) ? calls : [calls], + this.signedSession + ); + const nonce = toBN(transactionsDetail.nonce ?? (await this.getNonce())); + let maxFee: BigNumberish = '0'; + if (transactionsDetail.maxFee || transactionsDetail.maxFee === 0) { + maxFee = transactionsDetail.maxFee; + } else { + const { suggestedMaxFee } = await this.estimateFee(transactions, { nonce }); + maxFee = suggestedMaxFee.toString(); + } + + const version = toBN(transactionVersion); + + const signerDetails: InvocationsSignerDetails = { + walletAddress: this.address, + nonce, + maxFee, + version, + chainId: this.chainId, + }; + + const signature = await this.signer.signTransaction(transactions, signerDetails, abis); + + const calldata = fromCallsToExecuteCalldataWithNonce(transactions, nonce); + + return this.invokeFunction( + { contractAddress: this.address, entrypoint: '__execute__', calldata, signature }, + { + maxFee, + version, + } + ); + } +} diff --git a/src/signer/default.ts b/src/signer/default.ts index 828212090..464f53562 100644 --- a/src/signer/default.ts +++ b/src/signer/default.ts @@ -1,5 +1,5 @@ import { Abi, Invocation, InvocationsSignerDetails, KeyPair, Signature } from '../types'; -import { getStarkKey, sign } from '../utils/ellipticCurve'; +import { genKeyPair, getStarkKey, sign } from '../utils/ellipticCurve'; import { calculcateTransactionHash, getSelectorFromName } from '../utils/hash'; import { fromCallsToExecuteCalldataWithNonce } from '../utils/transaction'; import { TypedData, getMessageHash } from '../utils/typedData'; @@ -8,7 +8,7 @@ import { SignerInterface } from './interface'; export class Signer implements SignerInterface { protected keyPair: KeyPair; - constructor(keyPair: KeyPair) { + constructor(keyPair: KeyPair = genKeyPair()) { this.keyPair = keyPair; } diff --git a/src/utils/number.ts b/src/utils/number.ts index 08f3b2e4e..8d1d57db8 100644 --- a/src/utils/number.ts +++ b/src/utils/number.ts @@ -6,7 +6,7 @@ import { addHexPrefix, removeHexPrefix } from './encode'; export type BigNumberish = string | number | BN; export function isHex(hex: string): boolean { - return hex.startsWith('0x'); + return /^0x[0-9a-f]*$/i.test(hex); } export function toBN(number: BigNumberish, base?: number | 'hex') { diff --git a/src/utils/session.ts b/src/utils/session.ts new file mode 100644 index 000000000..56de59551 --- /dev/null +++ b/src/utils/session.ts @@ -0,0 +1,73 @@ +import type { AccountInterface } from '../account'; +import { Signature } from '../types'; +import { getSelectorFromName, pedersen } from './hash'; +import { MerkleTree } from './merkle'; +import { isHex } from './number'; +import { StarkNetDomain } from './typedData'; + +interface Policy { + contractAddress: string; + selector: string; +} + +interface BaseSession { + key: string; + expires: number; +} + +export interface RequestSession extends BaseSession { + policies: Policy[]; +} + +export interface PreparedSession extends BaseSession { + root: string; +} + +export interface SignedSession extends PreparedSession { + signature: Signature; +} + +export function prepareSession(session: RequestSession): PreparedSession { + const { policies, ...rest } = session; + const { root } = new MerkleTree( + policies.map(({ contractAddress, selector }) => + pedersen([contractAddress, isHex(selector) ? selector : getSelectorFromName(selector)]) + ) + ); + return { ...rest, root }; +} + +export async function createSession( + session: RequestSession, + account: AccountInterface, + domain: StarkNetDomain = {} +): Promise { + const { key, expires, root } = prepareSession(session); + const signature = await account.signMessage({ + primaryType: 'Session', + types: { + Session: [ + { name: 'key', type: 'felt' }, + { name: 'expires', type: 'felt' }, + { name: 'root', type: 'felt' }, + ], + StarkNetDomain: [ + { name: 'name', type: 'felt' }, + { name: 'version', type: 'felt' }, + { name: 'chain_id', type: 'felt' }, + ], + }, + domain, + message: { + key, + expires, + root, + }, + }); + return { + key, + expires, + root, + signature, + }; +} diff --git a/www/guides/session.md b/www/guides/session.md new file mode 100644 index 000000000..101f132a8 --- /dev/null +++ b/www/guides/session.md @@ -0,0 +1,92 @@ +# How to use Sessions + +Sessions can be used to make a user allow a bunch of transactions once and allow the dapp to execute these transactions as many times as they want, only limited by the policies signed. +A session kind of looks like this: + +```typescript +interface Policy { + contractAddress: string; + selector: string; +} + +interface Session { + key: string; + expires: number; + policies: Policy[]; +} +``` + +## Using sessions as a dapp + +First you need to have a valid account with a valid Signer. You can either get that by using the Account and Signer classes provided by starknet.js, or use an injected instance by a wallet. + +```typescript +const account = window.starknet.account +``` + +Next you need to come up with the permissions you would like for your session. You also need to generate the session keypair you want to grant these rights to. + +This example session will allow the dapp to execute erc20 transfers on the specified token without asking the user to approve the transaction again. After signing the session the dapp can execute all transactions listed in `policies` whenever it wants and as many times as it wants. + +```typescript +import { Signer, ec } from "starknet" + +// gets signer with random private key you need to store if you want to reuse the session +const sessionSigner = new Signer() + +const session: Session = { + key: await sessionSigner.getPublicKey(), + expires: Date.now() + 1000 * 60 * 60 * 24, // 1 day + policies: [ + { + // lets assume this is a erc20 contract + contractAddress: '0x...', + selector: 'transfer', + }, + ], +} +``` + +Now you can sign the session with the account you have. +Depending on how your account works, the user may get asked to sign a message + +```typescript +import { session } from "starknet" + +// calls account.signMessage internally +const signedSession = await session.createSession(session, account) +``` + +### Using established sessions + +With your signed session you can now use it with your dapp to do transactions without the user having to approve again. + +```typescript +import { SessionAccount } from "starknet" + +const sessionAccount = new SessionAccount(account, account.address, sessionSigner, signedSession) + +// this transaction should get executed without the user having to approve again +const tx = sessionAccount.execute({ + // lets assume this is a erc20 contract + contractAddress: '0x...', + selector: 'transfer', + calldata: [ + '0x...', // address of the recipient + '1', // amount of tokens to transfer + ], +}) +``` + +You can also use the session when you dont have access to the main account (`window.starknet.account`). You only need access to the `signedSession` object and the `sessionSigner`. + +```typescript +const sessionAccount = new SessionAccount( + providerWithCorrectNetwork, + "0xaccountAddress", + sessionSigner, + signedSession +) +``` + +Congratulations, you can now use your dapp to execute transactions without the user having to approve!