Skip to content

Commit

Permalink
feat: v4.3 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugo0 committed Feb 7, 2024
1 parent 4b8caa7 commit 49c82e8
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 74 deletions.
7 changes: 7 additions & 0 deletions SOP.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,10 @@ EVM:
- update contracts.json (copied from peanut-contracts repo)
- update data.ts exports, other imports
- update LATEST_CONTRACT_VERSION ... in data ts.
- update signWithdrawalMessage
- update eip712domains.ts
- update createClaimXChainPayload
- update getLinkDetails
- update prepareRaffleDepositTxs
- getRaffleInfo +++++
- just CTRL+F for 'v4.2' or 'v4.3'
4 changes: 2 additions & 2 deletions src/consts/eip712domains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,5 @@ export const GaslessReclaimTypes: any = {
GaslessReclaim: [{ name: 'depositIndex', type: 'uint256' }],
}

export const PeanutsWithEIP3009: Array<string> = ['v4.2']
export const PeanutsWithGaslessRevoke: Array<string> = ['v4.2']
export const PeanutsWithEIP3009: Array<string> = ['v4.2', 'v4.3']
export const PeanutsWithGaslessRevoke: Array<string> = ['v4.2', 'v4.3']
17 changes: 10 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1284,13 +1284,15 @@ async function claimLink({
txOptions,
provider: signer.provider,
})
txOptions = { ...txOptions, ...claimParams }

const txOptions2 = { ...txOptions, ...claimParams }

config.verbose && console.log('submitting tx on contract address: ', contract.address, 'on chain: ', chainId, '...')
config.verbose && console.log('Full tx:', txOptions)
config.verbose && console.log('Full tx:', txOptions2)
config.verbose && console.log('Full tx:', claimParams, txOptions)

// withdraw the deposit
const tx = await contract.withdrawDeposit(txOptions)
const tx = await contract.withdrawDeposit(...claimParams, txOptions)
console.log('submitted tx: ', tx.hash, ' now waiting for receipt...')
const txReceipt = await tx.wait()

Expand Down Expand Up @@ -1426,7 +1428,7 @@ async function createClaimXChainPayload({
const contractVersion = linkParams.contractVersion
const password = linkParams.password

if (contractVersion !== 'v4.2') {
if (contractVersion !== 'v4.2' && contractVersion !== 'v4.3') {
throw new interfaces.SDKStatus(
interfaces.EXChainStatusCodes.ERROR_UNSUPPORTED_CONTRACT_VERSION,
`Unsupported contract version ${contractVersion}`
Expand Down Expand Up @@ -1607,7 +1609,7 @@ async function getLinkDetails({ link, provider }: interfaces.IGetLinkDetailsPara
}

let depositDate: Date | null = null
if (['v4', 'v4.2'].includes(contractVersion)) {
if (['v4', 'v4.2', 'v4.3'].includes(contractVersion)) {
if (deposit.timestamp) {
depositDate = new Date(deposit.timestamp * 1000)
if (deposit.timestamp == 0) {
Expand Down Expand Up @@ -2101,8 +2103,8 @@ function getLatestContractVersion({
experimental?: boolean
}): string {
try {
config.verbose && console.log('getting LatestContractVersion:', chainId, type, experimental)
const data = PEANUT_CONTRACTS

const chainData = data[chainId as unknown as keyof typeof data]

// Filter keys starting with "v" or "Bv" based on type
Expand All @@ -2123,6 +2125,7 @@ function getLatestContractVersion({
return (partsB[1] || 0) - (partsA[1] || 0)
})

config.verbose && console.log('Contract Versions found:', versions)
// Adjust the filtering logic based on the experimental flag and contract version variables
if (!experimental && type === 'normal') {
if (!versions.includes(LATEST_STABLE_CONTRACT_VERSION)) {
Expand Down Expand Up @@ -2156,7 +2159,7 @@ async function getAllUnclaimedDepositsWithIdxForAddress({
provider = await getDefaultProvider(chainId)
}

if (!['v4', 'v4.2'].includes(peanutContractVersion)) {
if (!['v4', 'v4.2', 'v4.3'].includes(peanutContractVersion)) {
console.error('ERROR: can only return unclaimed deposits for v4+ contracts')
return
}
Expand Down
77 changes: 45 additions & 32 deletions src/raffle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,12 @@ export async function prepareRaffleDepositTxs({
}

// For simplicity doing raffles always on these contracts
const peanutContractVersion = 'v4.2'
const batcherContractVersion = 'Bv4.2'
const peanutContractVersion = 'v4.3'
const batcherContractVersion = 'Bv4.3'

if (!provider) {
provider = await getDefaultProvider(linkDetails.chainId)
}

const tokenAmountString = trim_decimal_overflow(linkDetails.tokenAmount, linkDetails.tokenDecimals)
const tokenAmountBigNum = ethers.utils.parseUnits(tokenAmountString, linkDetails.tokenDecimals)
const peanutVaultAddress = getContractAddress(linkDetails.chainId, peanutContractVersion)
Expand Down Expand Up @@ -156,7 +155,7 @@ export async function getRaffleLinkFromTx({
linkDetails,
txHash,
passwords: Array(numberOfLinks).fill(password),
provider
provider,
})
console.log('Links!!', links)

Expand All @@ -174,7 +173,7 @@ export async function getRaffleLinkFromTx({
} catch (error: any) {
console.error(
'Bad that we got an error from the events api, but not stopping the entire link creation because of this',
error,
error
)
}

Expand All @@ -195,30 +194,34 @@ export function validateRaffleLink({ link }: interfaces.IValidateRaffleLink) {
const password = linksParams[0].password
const trackId = linksParams[0].trackId

if (chainId === '' || contractVersion === '' || password === '') throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
`chainId, contractVersion or password is empty for raffle link ${link}`
)
if (chainId === '' || contractVersion === '' || password === '')
throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
`chainId, contractVersion or password is empty for raffle link ${link}`
)

linksParams.forEach((params) => {
if ( // must be the same for all links
if (
// must be the same for all links
params.chainId !== chainId ||
params.contractVersion !== contractVersion ||
params.password !== password ||
params.trackId !== trackId
) throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
`chainId, contractVersion, password or trackId is not consistent for raffle link ${link}`
)
throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
`chainId, contractVersion, password or trackId is not consistent for raffle link ${link}`
)
})

// deposit indices must be sequential
let prevDepositIndex = linksParams[0].depositIdx
linksParams.slice(1).forEach((params) => {
if (params.depositIdx !== prevDepositIndex + 1) throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
`deposit indices are not sequential for raffle link ${link}`
)
if (params.depositIdx !== prevDepositIndex + 1)
throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
`deposit indices are not sequential for raffle link ${link}`
)
prevDepositIndex = params.depositIdx
})

Expand All @@ -233,7 +236,7 @@ export async function hasAddressParticipatedInRaffle({
address,
link,
APIKey,
baseUrl
baseUrl,
}: interfaces.IIsAddressEligible): Promise<boolean> {
const leaderboard = await getRaffleLeaderboard({
link,
Expand All @@ -250,7 +253,12 @@ export async function hasAddressParticipatedInRaffle({
return false
}

export async function getRaffleInfo({ link, provider, APIKey, baseUrl }: interfaces.IGetRaffleInfoParams): Promise<interfaces.IRaffleInfo> {
export async function getRaffleInfo({
link,
provider,
APIKey,
baseUrl,
}: interfaces.IGetRaffleInfoParams): Promise<interfaces.IRaffleInfo> {
const links = getLinksFromMultilink(link)

const linksParams: interfaces.ILinkParams[] = []
Expand All @@ -261,10 +269,10 @@ export async function getRaffleInfo({ link, provider, APIKey, baseUrl }: interfa
const depositIndices: number[] = []
linksParams.forEach((params) => depositIndices.push(params.depositIdx))

if (peanutVersion !== 'v4.2') {
if (peanutVersion !== 'v4.3') {
throw new interfaces.SDKStatus(
interfaces.ERaffleErrorCodes.ERROR_VALIDATING_LINK_DETAILS,
'Raffles only work with peanut contract v4.2'
'Raffles only work with peanut contract v4.3'
)
}

Expand Down Expand Up @@ -389,9 +397,14 @@ export async function claimRaffleLink({
})
} catch (error: any) {
const newRaffleInfo = await getRaffleInfo({ link, provider })
const updatedSlotInfo = newRaffleInfo.slotsDetails.find((slot) => slot._depositIndex === slotToClaim._depositIndex)
const updatedSlotInfo = newRaffleInfo.slotsDetails.find(
(slot) => slot._depositIndex === slotToClaim._depositIndex
)
if (updatedSlotInfo.claimed) {
console.log(`Slot ${slotIndexToClaim} has already been claimed, will retry claiming a different slot`, error)
console.log(
`Slot ${slotIndexToClaim} has already been claimed, will retry claiming a different slot`,
error
)
continue
} else {
console.log('An unexpected error occured while claiming a raffle slot!', error)
Expand All @@ -415,7 +428,7 @@ export async function claimRaffleLink({
} catch (error: any) {
console.error(
'Bad that we got an error from the events api, but not stopping the entire link claim because of this',
error,
error
)
}

Expand All @@ -436,7 +449,7 @@ export async function addUsername({
name,
link,
APIKey,
baseUrl = 'https://api.peanut.to/add-username'
baseUrl = 'https://api.peanut.to/add-username',
}: interfaces.IAddUsername) {
const res = await fetch(baseUrl, {
method: 'POST',
Expand All @@ -462,7 +475,7 @@ export async function getUsername({
address,
link,
APIKey,
baseUrl = 'https://api.peanut.to/get-username'
baseUrl = 'https://api.peanut.to/get-username',
}: interfaces.IGetUsername): Promise<string | null> {
const res = await fetch(baseUrl, {
method: 'POST',
Expand Down Expand Up @@ -497,7 +510,7 @@ export async function addLinkClaim({
amount,
link,
APIKey,
baseUrl = 'https://api.peanut.to/add-link-claim'
baseUrl = 'https://api.peanut.to/add-link-claim',
}: interfaces.IAddLinkClaim) {
const res = await fetch(baseUrl, {
method: 'POST',
Expand Down Expand Up @@ -527,7 +540,7 @@ export async function addLinkCreation({
amount,
link,
APIKey,
baseUrl = 'https://api.peanut.to/add-link-creation'
baseUrl = 'https://api.peanut.to/add-link-creation',
}: interfaces.IAddLinkCreation) {
const res = await fetch(baseUrl, {
method: 'POST',
Expand All @@ -553,7 +566,7 @@ export async function addLinkCreation({
export async function getRaffleLeaderboard({
link,
APIKey,
baseUrl = 'https://api.peanut.to/get-raffle-leaderboard'
baseUrl = 'https://api.peanut.to/get-raffle-leaderboard',
}: interfaces.IGetRaffleLeaderboard): Promise<interfaces.IRaffleLeaderboardEntry[]> {
const res = await fetch(baseUrl, {
method: 'POST',
Expand All @@ -577,7 +590,7 @@ export async function getRaffleLeaderboard({
}

export async function getGenerosityLeaderboard({
baseUrl = 'https://api.peanut.to/get-generosity-leaderboard'
baseUrl = 'https://api.peanut.to/get-generosity-leaderboard',
}: interfaces.IGetLeaderboard): Promise<interfaces.IGenerosityLeaderboardEntry[]> {
const res = await fetch(baseUrl, {
method: 'POST',
Expand All @@ -598,7 +611,7 @@ export async function getGenerosityLeaderboard({
}

export async function getPopularityLeaderboard({
baseUrl = 'https://api.peanut.to/get-popularity-leaderboard'
baseUrl = 'https://api.peanut.to/get-popularity-leaderboard',
}: interfaces.IGetLeaderboard): Promise<interfaces.IPopularityLeaderboardEntry[]> {
const res = await fetch(baseUrl, {
method: 'POST',
Expand All @@ -616,4 +629,4 @@ export async function getPopularityLeaderboard({

const json = await res.json()
return json.leaderboard
}
}
4 changes: 2 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ export async function signWithdrawalMessage(
depositIdx: number,
recipient: string,
privateKey: string,
onlyRecipientMode?: boolean // only for v4.2
onlyRecipientMode?: boolean // only for v4.2+
) {
let claimParams: any[]
if (vaultVersion == 'v4.2') {
if (vaultVersion == 'v4.2' || vaultVersion == 'v4.3') {
const extraData = onlyRecipientMode ? RECIPIENT_WITHDRAWAL_MODE : ANYONE_WITHDRAWAL_MODE
const stringHash = ethers.utils.solidityKeccak256(
['bytes32', 'uint256', 'address', 'uint256', 'address', 'bytes32'],
Expand Down
10 changes: 5 additions & 5 deletions test/basic/setFeeOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('setFeeOptions function', () => {
expect(txOptions).toHaveProperty('maxFeePerGas')
expect(txOptions).toHaveProperty('maxPriorityFeePerGas')
expect(BigInt(txOptions.maxPriorityFeePerGas)).toBeLessThanOrEqual(BigInt(txOptions.maxFeePerGas))
})
}, 30000)

it('should correctly set fee options for non-EIP-1559 chains', async () => {
const provider = await getDefaultProvider('56')
Expand All @@ -35,7 +35,7 @@ describe('setFeeOptions function', () => {
})

expect(txOptions).toHaveProperty('gasPrice')
})
}, 30000)

it('should correctly set gas limit for specific chains', async () => {
const provider = await getDefaultProvider('137')
Expand All @@ -47,7 +47,7 @@ describe('setFeeOptions function', () => {

expect(txOptions).toHaveProperty('gasLimit')
expect(txOptions.gasLimit.toString()).toEqual('1000000')
})
}, 30000)

it('should correctly set maxPriorityFeePerGas for specific chains', async () => {
const provider = await getDefaultProvider('1')
Expand All @@ -59,7 +59,7 @@ describe('setFeeOptions function', () => {

expect(txOptions).toHaveProperty('maxPriorityFeePerGas')
expect(txOptions.maxPriorityFeePerGas.toString()).toEqual(ethers.utils.parseUnits('30', 'gwei').toString())
})
}, 30000)

it('should throw an error if provider fails to fetch gas price', async () => {
const faultyProvider = new ethers.providers.JsonRpcProvider({
Expand All @@ -72,5 +72,5 @@ describe('setFeeOptions function', () => {
provider: faultyProvider,
})
).rejects.toThrow()
})
}, 30000)
})
Loading

0 comments on commit 49c82e8

Please sign in to comment.