Skip to content

Commit

Permalink
feat: add calculateContractAddressFromHash
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvkelawala committed Jun 15, 2022
1 parent b03500e commit e22c346
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
25 changes: 25 additions & 0 deletions __tests__/utils/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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();
});
});
24 changes: 23 additions & 1 deletion src/utils/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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);
}

0 comments on commit e22c346

Please sign in to comment.