From e22c3464036f97eee3c617d3790aac35b3d95379 Mon Sep 17 00:00:00 2001 From: Dhruv Kelawala Date: Wed, 15 Jun 2022 18:51:48 +0530 Subject: [PATCH] feat: add calculateContractAddressFromHash --- __tests__/utils/utils.test.ts | 25 +++++++++++++++++++++++++ src/utils/hash.ts | 24 +++++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/__tests__/utils/utils.test.ts b/__tests__/utils/utils.test.ts index decef618e..2d87385ed 100644 --- a/__tests__/utils/utils.test.ts +++ b/__tests__/utils/utils.test.ts @@ -1,6 +1,7 @@ import fs from 'fs'; import { constants, hash, json, number, stark } from '../../src'; +import { pedersen } from '../../src/utils/hash'; const { IS_BROWSER } = constants; @@ -87,3 +88,27 @@ describe('estimatedFeeToMaxFee()', () => { expect(res).toBe(11_500); }); }); + +describe('Deterministic Address calculation', () => { + // This test just show how to use calculateContractAddressFromHash for new devs + + test.only('calculate hash', () => { + const ethAddress = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7'; + + const daiAddress = '0x03e85bfbb8e2a42b7bead9e88e9a1b19dbccf661471061807292120462396ec9'; + const factoryAddress = '0x249827618A01858A72B7D04339C47195A324D20D6037033DFE2829F98AFF4FC'; + const classHash = '0x55187E68C60664A947048E0C9E5322F9BF55F7D435ECDCF17ED75724E77368F'; + + // Any type of salt can be used. It depends on the dApp what kind of salt it wants to use. + const salt = pedersen([ethAddress, daiAddress]); + + const res = hash.calculateContractAddressFromHash( + salt, + classHash, + [ethAddress, daiAddress, factoryAddress], + factoryAddress + ); + + expect(res).not.toBeNull(); + }); +}); diff --git a/src/utils/hash.ts b/src/utils/hash.ts index 7df83cafd..5bcf02c6c 100644 --- a/src/utils/hash.ts +++ b/src/utils/hash.ts @@ -11,9 +11,10 @@ import { TransactionHashPrefix, ZERO, } from '../constants'; +import { RawCalldata } from '../types/lib'; import { ec } from './ellipticCurve'; import { addHexPrefix, buf2hex, utf8ToArray } from './encode'; -import { BigNumberish, toBN, toHex } from './number'; +import { BigNumberish, toBN, toFelt, toHex } from './number'; export const transactionVersion = 0; export const feeTransactionVersion = toBN(2).pow(toBN(128)).add(toBN(transactionVersion)); @@ -132,3 +133,24 @@ export function calculcateTransactionHash( chainId ); } + +export function calculateContractAddressFromHash( + salt: BigNumberish, + classHash: BigNumberish, + constructorCalldata: RawCalldata, + deployerAddress: BigNumberish +) { + const constructorCalldataHash = computeHashOnElements(constructorCalldata); + + const CONTRACT_ADDRESS_PREFIX = toFelt('0x535441524b4e45545f434f4e54524143545f41444452455353'); // Equivalent to 'STARKNET_CONTRACT_ADDRESS' + + const dataToHash = [ + CONTRACT_ADDRESS_PREFIX, + deployerAddress, + salt, + classHash, + constructorCalldataHash, + ]; + + return computeHashOnElements(dataToHash); +}