Skip to content

Commit

Permalink
⬆️ Update starknetjs (#120)
Browse files Browse the repository at this point in the history
* ⬆️ Update starknetjs

* ✅ Fix build

* 🐛 Fix signature verification

* 🐛 Fix starknet version

* 🔥 Remove not necessary check
  • Loading branch information
0xlny authored Jul 13, 2023
1 parent 7ca4c53 commit 04bd5e6
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 160 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"peerDependencies": {
"ethers": "^6.2.0",
"qs": "^6.11.0",
"starknet": "^4.22.0"
"starknet": "^5.14.1"
},
"devDependencies": {
"@babel/plugin-transform-modules-commonjs": "7.22.5",
Expand All @@ -74,7 +74,7 @@
"prettier": "2.8.8",
"qs": "6.11.2",
"size-limit": "8.2.6",
"starknet": "4.22.0",
"starknet": "5.14.1",
"tsup": "7.0.0",
"typedoc": "0.24.8",
"typescript": "5.0.4"
Expand Down
8 changes: 4 additions & 4 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { constants } from 'starknet';
export const STAGING_BASE_URL = 'https://goerli.api.avnu.fi';
export const BASE_URL = 'https://goerli.api.avnu.fi';
export const AVNU_ADDRESS: { [chainId: string]: string } = {
[constants.StarknetChainId.MAINNET]: '0x4270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f',
[`${constants.StarknetChainId.MAINNET}-dev`]: '0x4270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f',
[constants.StarknetChainId.TESTNET]: '0x6d8cd321dcbbf54512eab67c8a6849faf920077a3996f40bb4761adc4f021d2',
[`${constants.StarknetChainId.TESTNET}-dev`]: '0x871a5d57d3d89a451edfccb4a925bfbb712f960c69396d19ca12b3916fb1cd',
[constants.StarknetChainId.SN_MAIN]: '0x4270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f',
[`${constants.StarknetChainId.SN_MAIN}-dev`]: '0x4270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f',
[constants.StarknetChainId.SN_GOERLI]: '0x6d8cd321dcbbf54512eab67c8a6849faf920077a3996f40bb4761adc4f021d2',
[`${constants.StarknetChainId.SN_GOERLI}-dev`]: '0x871a5d57d3d89a451edfccb4a925bfbb712f960c69396d19ca12b3916fb1cd',
};
10 changes: 5 additions & 5 deletions src/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const aPrice = (): Price => ({
buyAmount: parseUnits('2', 18),
buyAmountInUsd: 1700,
blockNumber: 1,
chainId: constants.StarknetChainId.TESTNET,
chainId: constants.StarknetChainId.SN_GOERLI,
sourceName: 'AMM1',
priceRatioUsd: 0,
});
Expand All @@ -50,7 +50,7 @@ export const aQuote = (): Quote => ({
buyAmount: parseUnits('2', 18),
buyAmountInUsd: 1700,
blockNumber: 1,
chainId: constants.StarknetChainId.TESTNET,
chainId: constants.StarknetChainId.SN_GOERLI,
expiry: 100000000000,
routes: [
{
Expand Down Expand Up @@ -81,7 +81,7 @@ export const aQuoteWithManySubRoutes = (): Quote => ({
buyAmount: parseUnits('2', 18),
buyAmountInUsd: 1700,
blockNumber: 1,
chainId: constants.StarknetChainId.TESTNET,
chainId: constants.StarknetChainId.SN_GOERLI,
expiry: 100000000000,
priceRatioUsd: 0,
liquiditySource: 'DEX_AGGREGATOR',
Expand Down Expand Up @@ -130,7 +130,7 @@ export const aQuoteWithManyComplexRoutes = (): Quote => ({
buyAmount: parseUnits('2', 18),
buyAmountInUsd: 1700,
blockNumber: 1,
chainId: constants.StarknetChainId.TESTNET,
chainId: constants.StarknetChainId.SN_GOERLI,
expiry: 100000000000,
avnuFees: BigInt('0x0'),
avnuFeesInUsd: 0,
Expand Down Expand Up @@ -216,7 +216,7 @@ export const anInvokeSwapResponse = (): InvokeSwapResponse => ({
});

export const aBuildSwapTransaction = (): BuildSwapTransaction => ({
chainId: constants.StarknetChainId.TESTNET,
chainId: constants.StarknetChainId.SN_GOERLI,
contractAddress: '0x0',
entrypoint: 'execute',
calldata: [],
Expand Down
8 changes: 3 additions & 5 deletions src/services.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ import { parseUnits, toBeHex } from 'ethers';
import fetchMock from 'fetch-mock';
import qs from 'qs';
import { constants } from 'starknet';
import { TextEncoder } from 'util';
import { BASE_URL } from './constants';
import {
aBuildSwapTransaction,
anInvokeSwapResponse,
aPage,
aPair,
aPrice,
aPriceRequest,
aQuote,
Expand Down Expand Up @@ -296,7 +294,7 @@ describe('Avnu services', () => {
describe('buildApproveTx', () => {
it('should build approve', () => {
// When
const result = buildApproveTx('0x1', BigInt('1'), constants.StarknetChainId.TESTNET);
const result = buildApproveTx('0x1', BigInt('1'), constants.StarknetChainId.SN_GOERLI);

// Then
expect(result).toStrictEqual({
Expand All @@ -310,7 +308,7 @@ describe('Avnu services', () => {
describe('buildGetNonce', () => {
it('should build getNonce', () => {
// When
const result = buildGetNonce('0x1', constants.StarknetChainId.TESTNET);
const result = buildGetNonce('0x1', constants.StarknetChainId.SN_GOERLI);

// Then
expect(result).toStrictEqual({
Expand Down Expand Up @@ -343,7 +341,7 @@ describe('Avnu services', () => {
'0x052D8E9778d026588A51595E30B0f45609B4F771eEcF0E335CdeFeD1D84A9d89',
quote,
'0x0',
constants.StarknetChainId.TESTNET,
constants.StarknetChainId.SN_GOERLI,
);

// Then
Expand Down
29 changes: 19 additions & 10 deletions src/services.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { toBeHex } from 'ethers';
import qs from 'qs';
import { AccountInterface, Call, ec, hash, Signature, typedData, uint256 } from 'starknet';
import { AccountInterface, Call, ec, hash, Signature, stark, typedData, uint256 } from 'starknet';
import { AVNU_ADDRESS, BASE_URL, STAGING_BASE_URL } from './constants';
import {
AvnuOptions,
BuildSwapTransaction,
ExecuteSwapOptions,
GetPairsRequest,
GetTokensRequest,
InvokeSwapResponse,
Page,
Pair,
Price,
PriceRequest,
Quote,
Expand All @@ -34,13 +32,15 @@ const parseResponse = <T>(response: Response, avnuPublicKey?: string): Promise<T
if (avnuPublicKey) {
const signature = response.headers.get('signature');
if (!signature) throw new Error('No server signature');
const keyPair = ec.getKeyPairFromPublicKey(avnuPublicKey);
return response
.clone()
.text()
.then((textResponse) => {
const hashResponse = hash.computeHashOnElements([hash.starknetKeccak(textResponse)]);
if (!ec.verify(keyPair, hashResponse, signature.split(','))) throw new Error('Invalid server signature');
const formattedSig = signature.split(',').map((s) => BigInt(s));
const signatureType = new ec.starkCurve.Signature(formattedSig[0], formattedSig[1]);
if (!ec.starkCurve.verify(signatureType, hashResponse, avnuPublicKey))
throw new Error('Invalid server signature');
})
.then(() => response.json());
}
Expand Down Expand Up @@ -121,8 +121,15 @@ const fetchExecuteSwapTransaction = (
takerAddress?: string,
slippage?: number,
options?: AvnuOptions,
): Promise<InvokeSwapResponse> =>
fetch(`${options?.baseUrl ?? getBaseUrl()}/swap/v1/execute`, {
): Promise<InvokeSwapResponse> => {
let signature: string[] = [];

if (Array.isArray(takerSignature)) {
signature = takerSignature.map((sig) => toBeHex(BigInt(sig)));
} else if (takerSignature.r && takerSignature.s) {
signature = [toBeHex(BigInt(takerSignature.r)), toBeHex(BigInt(takerSignature.s))];
}
return fetch(`${options?.baseUrl ?? getBaseUrl()}/swap/v1/execute`, {
method: 'POST',
headers: {
Accept: 'application/json',
Expand All @@ -134,9 +141,10 @@ const fetchExecuteSwapTransaction = (
takerAddress,
nonce,
slippage,
takerSignature: takerSignature.map((signature) => toBeHex(BigInt(signature))),
takerSignature: signature,
}),
}).then((response) => parseResponse<InvokeSwapResponse>(response, options?.avnuPublicKey));
};

/**
* Build data for executing the exchange through AVNU router
Expand Down Expand Up @@ -331,7 +339,8 @@ const executeSwap = async (
{ executeApprove = true, gasless = false, takerSignature, slippage }: ExecuteSwapOptions = {},
options?: AvnuOptions,
): Promise<InvokeSwapResponse> => {
if (account.chainId !== quote.chainId) {
const chainId = await account.getChainId();
if (chainId !== quote.chainId) {
throw Error(`Invalid chainId`);
}

Expand All @@ -342,7 +351,7 @@ const executeSwap = async (
// /!\ Do not implement this yourself. It will change /!\
let nonce = undefined;
if (quote.liquiditySource === 'MARKET_MAKER' || gasless) {
const getNonce = buildGetNonce(account.address, account.chainId, options?.dev);
const getNonce = buildGetNonce(account.address, chainId, options?.dev);
const response = await account.callContract(getNonce);
nonce = response.result[0];
}
Expand Down
1 change: 1 addition & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defineConfig } from 'tsup';

export default defineConfig({
target: 'es2022',
entry: ['src/index.ts'],
sourcemap: true,
clean: true,
Expand Down
Loading

0 comments on commit 04bd5e6

Please sign in to comment.