before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
const { deployProxy, upgradeProxy } = require('@openzeppelin/truffle-upgrades');
const NFTStorage = artifacts.require("NFTStorage");
module.exports = async function (deployer, network, accounts) {
await upgradeProxy(NFTStorage.address, NFTStorage, { deployer });
};
| No issues found. | const { deployProxy, upgradeProxy } = require('@openzeppelin/truffle-upgrades');
const NFTStorage = artifacts.require("NFTStorage");
module.exports = async function (deployer, network, accounts) {
await upgradeProxy(NFTStorage.address, NFTStorage, { deployer });
};
| @@ -0,0 +1,7 @@
+const { deployProxy, upgradeProxy } = require('@openzeppelin/truffle-upgrades');
+
+const NFTStorage = artifacts.require("NFTStorage");
+
+module.exports = async function (deployer, network, accounts) {
+ await upgradeProxy(NFTStorage.address, NFTStorage, { deployer });
+}; | migrations/97_nftstorage_update.js | 0 | JavaScript | 1 | none | 16 | 8 | 8 | true | 781 nft bridge | 825 | CryptoBlades/cryptoblades | 321 | Vue | bilbolPrime | |
storedItemsOwners[address(_tokenAddress)][_id] = msg.sender;
_tokenAddress.safeTransferFrom(msg.sender, address(this), _id);
emit NFTStored(msg.sender, _tokenAddress, _id);
}
// Player withdraws NFT from storage.
function withdrawFromStorage(IERC721 _tokenAddress, uint256 _id)
... | No issues found. | storedItemsOwners[address(_tokenAddress)][_id] = msg.sender;
_tokenAddress.safeTransferFrom(msg.sender, address(this), _id);
emit NFTStored(msg.sender, _tokenAddress, _id);
}
// Player withdraws NFT from storage.
function withdrawFromStorage(IERC721 _tokenAddress, uint256 _id)
... | @@ -121,6 +121,9 @@ contract NFTStorage is IERC721ReceiverUpgradeable, Initializable, AccessControlU
// Transfer id => minted item Id; no need for NFT type; we can get that from trasnfer in info
mapping(uint256 => uint256) private _withdrawFromBridgeLog;
+ CryptoBlades public game;
+ uint256 private _... | contracts/NFTStorage.sol | 0 | Solidity | 1 | none | 16 | 51 | 51 | true | 781 nft bridge | 846 | CryptoBlades/cryptoblades | 321 | Vue | bilbolPrime | |
else {
out[stakeType] = Object.assign({}, stakingContractInfo, stakingContractAddressesFromBuild[stakeType]);
}
}
return out;
}
async function setUpStakingContracts(web3: Web3) {
networkId = getConfigValue('VUE_APP_NETWORK_ID') || '5777';
const stakingContractsInfo = getStakingContractsInfoWithD... | No issues found. | else {
out[stakeType] = Object.assign({}, stakingContractInfo, stakingContractAddressesFromBuild[stakeType]);
}
}
return out;
}
async function setUpStakingContracts(web3: Web3) {
networkId = getConfigValue('VUE_APP_NETWORK_ID') || '5777';
const stakingContractsInfo = getStakingContractsInfoWithD... | @@ -15,6 +15,7 @@ import { abi as weaponsAbi } from '../../build/contracts/Weapons.json';
import { abi as blacksmithAbi } from '../../build/contracts/Blacksmith.json';
import { abi as shieldsAbi } from '../../build/contracts/Shields.json';
import { abi as cbkLandSaleAbi } from '../../build/contracts/CBKLandSale.json... | frontend/src/contracts.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Frontend changes for merchandise purchasing #834 | 848 | CryptoBlades/cryptoblades | 321 | Vue | Cosy0o0 | |
case('trinket'):
trinketIds.push(nft.id.toString());
break;
case('junk'):
junkIds.push(nft.id.toString());
break;
case('keybox'):
keyLootboxIds.push(nft.id.toString());
break;
case('weapon'):
weaponIds.push(nft.id.toSt... | No issues found. | case('trinket'):
trinketIds.push(nft.id.toString());
break;
case('junk'):
junkIds.push(nft.id.toString());
break;
case('keybox'):
keyLootboxIds.push(nft.id.toString());
break;
case('weapon'):
weaponIds.push(nft.id.toSt... | @@ -281,6 +281,7 @@
@click="onNftClick(nft.type, nft.id)"
@contextmenu="canFavorite && toggleFavorite($event, nft.type, nft.id)"
>
+ <nft-options-dropdown v-if="showNftOptions" :nftType="nft.type" :nftId="nft.id" :options="options" class="nft-options"/>
<nft-icon :favo... | frontend/src/components/smart/NftList.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | add copy link option to the menu for items on the market | 851 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
nftPrice: new BigNumber(this.itemPrices.itemCharacterCosmeticContrastPrice).div(new BigNumber(10).pow(18)).toFixed(4).toString(),
name: i18n.t('market.nftList.characterContrast'),
description: i18n.t('market.nftList.characterContrastDesc'),
image: ''
},
{
... | No issues found. | nftPrice: new BigNumber(this.itemPrices.itemCharacterCosmeticContrastPrice).div(new BigNumber(10).pow(18)).toFixed(4).toString(),
name: i18n.t('market.nftList.characterContrast'),
description: i18n.t('market.nftList.characterContrastDesc'),
image: ''
},
{
... | @@ -681,7 +681,7 @@
</div>
</div>
</b-tab>
- <b-tab @click="clearData();browseTabActive = false;skillShopTabActive = false">
+ <b-tab v-if="isMerchandiseEnabled" @click="clearData();browseTabActive = false;skillShopTabActive = false">
<template #title>
{{$t('mark... | frontend/src/views/Market.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Add Merchandise feature flag | 902 | CryptoBlades/cryptoblades | 321 | Vue | Chriserus | |
this.duelResult.result = formattedResult.attackerRoll > formattedResult.defenderRoll ? 'win' : 'lose';
this.duelResult.attackerRoll = formattedResult.attackerRoll;
this.duelResult.defenderRoll = formattedResult.defenderRoll;
this.duelResult.skillDifference = this.duelResult.resul... | No issues found. | this.duelResult.result = formattedResult.attackerRoll > formattedResult.defenderRoll ? 'win' : 'lose';
this.duelResult.attackerRoll = formattedResult.attackerRoll;
this.duelResult.defenderRoll = formattedResult.defenderRoll;
this.duelResult.skillDifference = this.duelResult.resul... | @@ -21,7 +21,7 @@
<div class="characterImageWrapper">
<pvp-character :characterId="currentCharacterId" />
</div>
- <div class="info">
+ <div v-if="characterInformation" class="info">
<h1 class="characterName">{{ characterInformation.name }}</h1>
<div clas... | frontend/src/components/smart/PvPArenaMatchMaking.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Fix/pvp fixes | 922 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
name: '',
level: null,
rank: null
};
this.opponentActiveWeaponWithInformation = {
weaponId: null,
information: {}
};
this.opponentActiveShieldWithInformation = {
shieldId: null,
information: {}
};
},
kickCharacterFromArena(... | No issues found. | name: '',
level: null,
rank: null
};
this.opponentActiveWeaponWithInformation = {
weaponId: null,
information: {}
};
this.opponentActiveShieldWithInformation = {
shieldId: null,
information: {}
};
},
kickCharacterFromArena(... | @@ -160,6 +160,7 @@ export default {
leaveArena() {
this.isCharacterInArena = false;
+ this.isMatchMaking = false;
this.$emit('leaveMatchMaking');
},
@@ -170,7 +171,7 @@ export default {
this.opponentInformation.level = await this.contracts().Characters.methods.getLevel(defende... | frontend/src/components/smart/PvPArena.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Feat/pvp overhaul frontend | 978 | CryptoBlades/cryptoblades | 321 | Vue | RafaelVidaurre | |
delete _stakedNftOwner[id];
if (_userStakedNfts[msg.sender].length() == 0) {
_stakeTimestamp[msg.sender] = 0;
}
stakingToken.safeTransferFrom(address(this), msg.sender, id);
emit Withdrawn(msg.sender, id);
}
function bulkWithdraw(uint256[] calldata ids)
... | No issues found. | delete _stakedNftOwner[id];
if (_userStakedNfts[msg.sender].length() == 0) {
_stakeTimestamp[msg.sender] = 0;
}
stakingToken.safeTransferFrom(address(this), msg.sender, id);
emit Withdrawn(msg.sender, id);
}
function bulkWithdraw(uint256[] calldata ids)
... | @@ -171,8 +171,29 @@ contract NftStakingRewardsUpgradeable is
emit Staked(msg.sender, id);
}
- function withdraw(uint256 id)
+ function bulkStake(uint256[] memory ids)
public
+ virtual
+ override
+ normalMode
+ nonReentrant
+ whenNotPaused
+ updat... | contracts/staking/NftStakingRewardsUpgradeable.sol | 0 | Solidity | 1 | none | 16 | 51 | 51 | true | bulk staking | 979 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
this.loadCount = 0;
this.loadCountTotal = 15;
const blade = (this.weapon.blade % bladeCount)+1;
const crossGuard = (this.weapon.crossguard % crossGuardCount)+1;
const grip = (this.weapon.grip % gripCount)+1;
const pommel = (this.weapon.pommel % pommelCount)+1;
// i fucked up,... | No issues found. | this.loadCount = 0;
this.loadCountTotal = 15;
const blade = (this.weapon.blade % bladeCount)+1;
const crossGuard = (this.weapon.crossguard % crossGuardCount)+1;
const grip = (this.weapon.grip % gripCount)+1;
const pommel = (this.weapon.pommel % pommelCount)+1;
// i fucked up,... | @@ -132,8 +132,9 @@ export default {
if(this.weapon.element) {
ttHtml += `<br>Element: ${wrapInSpan(this.weapon.element, this.weapon.element)}`;
}
-
+ const avg = [];
if(this.weapon.stat1Value) {
+ avg.push(this.weapon.stat1Value);
ttHtml += `<br>${wrapInSpan(this.weap... | frontend/src/components/WeaponIcon.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Avg weapon stat | 1,004 | CryptoBlades/cryptoblades | 321 | Vue | Sellie96 | |
return weapon.information.element === this.weaponElementFilter;
});
}
} else {
if (!this.weaponElementFilter) {
this.filteredWeaponsWithInformation = this.ownedWeaponsWithInformation.filter((weapon) => {
return weapon.information.stars === value - 1;
... | No issues found. | return weapon.information.element === this.weaponElementFilter;
});
}
} else {
if (!this.weaponElementFilter) {
this.filteredWeaponsWithInformation = this.ownedWeaponsWithInformation.filter((weapon) => {
return weapon.information.stars === value - 1;
... | @@ -17,59 +17,78 @@
<pvp-separator dark vertical />
<div class="weaponsWrapper">
<div v-if="!selectedWeaponId" :class="{ disabledStyles: ownedWeaponsWithInformation.length === 0 }" class="weaponButtonWrapper">
- <button class="selectWeaponButton" id="weapon-popove... | frontend/src/components/smart/PvPArenaPreparation.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Feat/pvp weapons info | 1,011 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
ownedChunkIds(): string[] {
const uniqChunkIds = _.uniq(this.ownedLands.map(x => +x.chunkId)).sort((a, b) => a - b).map(x => x.toString());
return [''].concat(uniqChunkIds);
}
},
watch: {
async nftsToDisplay(newNftsToDisplay: NftIdType[]) {
const shieldIds: string[] = [];
const ... | No issues found. | ownedChunkIds(): string[] {
const uniqChunkIds = _.uniq(this.ownedLands.map(x => +x.chunkId)).sort((a, b) => a - b).map(x => x.toString());
return [''].concat(uniqChunkIds);
}
},
watch: {
async nftsToDisplay(newNftsToDisplay: NftIdType[]) {
const shieldIds: string[] = [];
const ... | @@ -349,6 +349,7 @@ interface Data {
showFavoriteNfts: boolean;
landSaleAllowed: boolean;
canPurchaseLand: boolean;
+ canPurchaseShield: boolean;
purchase: Land | undefined;
selectedTier: number;
selectedCurrency: number;
@@ -438,6 +439,7 @@ interface StoreMappedActions {
claimPlayerReservedLand(p... | frontend/src/components/smart/NftList.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Add frontend lockout to additional shield purchases | 1,017 | CryptoBlades/cryptoblades | 321 | Vue | krisukox | |
this.loading = false;
},
async listenForDuel(contracts) {
const currentBlock = await this.web3.eth.getBlockNumber();
const subscription = this.web3.eth.subscribe('newBlockHeaders', async () => {
const duelFinishedResult = await contracts.PvpArena.getPastEvents('DuelFinished', {
... | No issues found. | this.loading = false;
},
async listenForDuel(contracts) {
const currentBlock = await this.web3.eth.getBlockNumber();
const subscription = this.web3.eth.subscribe('newBlockHeaders', async () => {
const duelFinishedResult = await contracts.PvpArena.getPastEvents('DuelFinished', {
... | @@ -130,6 +130,11 @@
:userCurrentRank="duelResult.rankDifference"
@close-modal="handleCloseModal"
/>
+ <pvp-under-attack-modal
+ v-if="this.isUnderAttack"
+ :isUnderAttack="isUnderAttack"
+ @close-modal="handleCloseAttackModal"
+ />
</div>
</template>
@@ -146,6 +151,7 @@ im... | frontend/src/components/smart/PvPArenaMatchMaking.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Feat/pvp add under attack modal | 1,033 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
.getTargets(characterId, weaponId)
.call(defaultCallOptions(state));
commit('updateTargets', { characterId, weaponId, targets: targets.map(targetFromContract) });
},
async doEncounter({ state, dispatch }, { characterId, weaponId, targetString, fightMultiplier }) {
if(fe... | No issues found. | .getTargets(characterId, weaponId)
.call(defaultCallOptions(state));
commit('updateTargets', { characterId, weaponId, targets: targets.map(targetFromContract) });
},
async doEncounter({ state, dispatch }, { characterId, weaponId, targetString, fightMultiplier }) {
if(fe... | @@ -97,7 +97,8 @@ const defaultStakeOverviewState: IStakeOverviewState = {
rewardRate: '0',
rewardsDuration: 0,
totalSupply: '0',
- minimumStakeTime: 0
+ minimumStakeTime: 0,
+ rewardDistributionTimeLeft: 0
};
export function createStore(web3: Web3) {
@@ -2150,18 +2151,21 @@ export function createStore(... | frontend/src/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add exclamation mark to indicate rewards in staking pool | 1,036 | CryptoBlades/cryptoblades | 321 | Vue | krisukox | |
}
console.error(e);
throw e;
}
this.pollCharactersStaminaIntervalId = setInterval(async () => {
this.ownCharacters.forEach(async (c) => {
await this.updateCharacterStamina(c.id);
});
this.ownGarrisonCharacters.forEach(async (c) => {
await this.updateCharacte... | No issues found. | }
console.error(e);
throw e;
}
this.pollCharactersStaminaIntervalId = setInterval(async () => {
this.ownCharacters.forEach(async (c) => {
await this.updateCharacterStamina(c.id);
});
this.ownGarrisonCharacters.forEach(async (c) => {
await this.updateCharacte... | @@ -88,6 +88,8 @@ import { apiUrl } from './utils/common';
import i18n from './i18n';
import { getConfigValue } from './contracts';
import '@/mixins/general';
+import config from '../app-config.json';
+import { addChainToRouter } from '@/utils/common';
Vue.directive('visible', (el, bind) => {
el.style.visibili... | frontend/src/App.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | resolves #1031 | 1,040 | CryptoBlades/cryptoblades | 321 | Vue | kevinunger | |
};
},
methods: {
close() {
this.showModal = false;
this.$emit('close-modal');
},
},
updated() {
if (this.result) {
this.showModal = true;
} else {
this.showModal = false;
}
},
watch: {
showModal() {
if (this.showModal) {
document.body.clas... | No issues found. | };
},
methods: {
close() {
this.showModal = false;
this.$emit('close-modal');
},
},
updated() {
if (this.result) {
this.showModal = true;
} else {
this.showModal = false;
}
},
watch: {
showModal() {
if (this.showModal) {
document.body.clas... | @@ -14,8 +14,16 @@
{{$t('pvp.youRolled')}}
</span>
<span class="chevron">></span>
- <span>{{ attackerRoll }}</span>
+ <span>{{attackerRoll}}</span>
</li>
+ <li>
+ <span>
+ {{$t('pvp.attackerPower')}}
+ </span>
+ <... | frontend/src/components/smart/PvPDuelModal.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Feat/pvp misc and leaderboards | 1,048 | CryptoBlades/cryptoblades | 321 | Vue | Dvidaurre | |
import {market, merchandise, portal, pvp, raid, stakeOnly} from './feature-flags';
import Merchandise from '@/components/smart/Merchandise.vue';
import {currentChainSupportsMerchandise, currentChainSupportsPvP} from '@/utils/common';
export default function createRouter() {
if (stakeOnly) {
return new VueRouter(... | No issues found. | import {market, merchandise, portal, pvp, raid, stakeOnly} from './feature-flags';
import Merchandise from '@/components/smart/Merchandise.vue';
import {currentChainSupportsMerchandise, currentChainSupportsPvP} from '@/utils/common';
export default function createRouter() {
if (stakeOnly) {
return new VueRouter(... | @@ -1,4 +1,4 @@
-import VueRouter, { RouteConfig } from 'vue-router';
+import VueRouter from 'vue-router';
import Plaza from './views/Plaza.vue';
import Blacksmith from './views/Blacksmith.vue';
@@ -15,76 +15,70 @@ import NftDisplay from './views/NftDisplay.vue';
import Bridge from './views/Bridge.vue';
import Tr... | frontend/src/router.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add PvP chain support checks, adjust merchandise chain check | 1,053 | CryptoBlades/cryptoblades | 321 | Vue | Chriserus | |
garrisonTabActive: boolean;
showAds: boolean;
soulCreationActive: boolean;
burnCharacterIds: string[];
remainingCharactersIds: string[];
targetCharacterId: string;
burnOption: number;
soulBalance: number;
burnCost: number;
isUpgrading: boolean;
soulAmount: number;
remainingPowerLimit: number;
... | No issues found. | garrisonTabActive: boolean;
showAds: boolean;
soulCreationActive: boolean;
burnCharacterIds: string[];
remainingCharactersIds: string[];
targetCharacterId: string;
burnOption: number;
soulBalance: number;
burnCost: number;
isUpgrading: boolean;
soulAmount: number;
remainingPowerLimit: number;
... | @@ -122,7 +122,7 @@
<div v-if="burnOption === 0 && !isUpgrading" class="d-flex flex-column mt-3 align-items-center">
<div class="soul-image" />
<h2>Soul</h2>
- <h2>{{soulBalance}} (+{{burnPower/10}})</h2>
+ <h2>{{soulBalance}} (+{{Math.floor... | frontend/src/views/Plaza.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Garrison xp | 1,088 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
if(minter != address(0) && minter != address(0x000000000000000000000000000000000000dEaD) && !hasRole(NO_OWNED_LIMIT, minter) && balanceOf(minter) >= characterLimit) {
receiver = address(garrison);
garrison.redirectToGarrison(minter, tokenID);
_mint(address(garrison), tokenID)... | No issues found. | if(minter != address(0) && minter != address(0x000000000000000000000000000000000000dEaD) && !hasRole(NO_OWNED_LIMIT, minter) && balanceOf(minter) >= characterLimit) {
receiver = address(garrison);
garrison.redirectToGarrison(minter, tokenID);
_mint(address(garrison), tokenID)... | @@ -7,6 +7,8 @@ import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Promos.sol";
import "./util.sol";
import "./Garrison.sol";
+import "./common.sol";
+
contract Characters is Initializable, ERC721Upgradeable, AccessControlUpgradeable {
using SafeMath for uint16;
@@ -310,18 +312,7 @@ contract Chara... | contracts/characters.sol | 0 | Solidity | 1 | none | 16 | 51 | 51 | true | Add getPowerAtLevel() to common.sol | 1,106 | CryptoBlades/cryptoblades | 321 | Vue | brian-man | |
unlockTimeLeft: parseInt(unlockTimeLeft, 10)
};
commit('updateStakeData', stakeData);
},
async stake({ state, dispatch }, { amount, stakeType }: { amount: string, stakeType: StakeType }) {
const { StakingRewards, StakingToken } = getStakingContracts(state.contracts(), stak... | No issues found. | unlockTimeLeft: parseInt(unlockTimeLeft, 10)
};
commit('updateStakeData', stakeData);
},
async stake({ state, dispatch }, { amount, stakeType }: { amount: string, stakeType: StakeType }) {
const { StakingRewards, StakingToken } = getStakingContracts(state.contracts(), stak... | @@ -3983,6 +3983,7 @@ export function createStore(web3: Web3) {
const { NFTStorage, Weapons, Characters, Shields } = state.contracts();
if(!NFTStorage || !Weapons || !Characters || !Shields || !state.defaultAccount) return;
+
const NFTContract: Contract<IERC721> =
nftContractAddr... | frontend/src/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | added shields for bridging | 1,109 | CryptoBlades/cryptoblades | 321 | Vue | kevinunger | |
});
describe("unhappy path", () => {
it("reverts if decision time expired", async () => {
await time.increase(await pvpArena.decisionSeconds());
await pvpArena.findOpponent(character1ID, {
from: accounts[1],
});
await time.increase(await pvpArena.decisionSeconds... | No issues found. | });
describe("unhappy path", () => {
it("reverts if decision time expired", async () => {
await time.increase(await pvpArena.decisionSeconds());
await pvpArena.findOpponent(character1ID, {
from: accounts[1],
});
await time.increase(await pvpArena.decisionSeconds... | @@ -134,7 +134,7 @@ contract("PvpArena", (accounts) => {
beforeEach(async () => {
weaponId = await helpers.createWeapon(accounts[1], "123", 0, { weapons });
- shieldId = await helpers.createShield(accounts[1], "123", { shields });
+ shieldId = await helpers.createShield(accounts[1], 0, "123", { ... | test/pvp-arena.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Feat/pvp ranked rewards on burnt chars | 1,120 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
if(!StakingRewards || !StakingToken) return;
await StakingToken.methods.approve(StakingRewards.options.address, amount).send({
from: state.defaultAccount
});
await StakingRewards.methods.stake(amount).send({
from: state.defaultAccount,
});
await dis... | No issues found. | if(!StakingRewards || !StakingToken) return;
await StakingToken.methods.approve(StakingRewards.options.address, amount).send({
from: state.defaultAccount
});
await StakingRewards.methods.stake(amount).send({
from: state.defaultAccount,
});
await dis... | @@ -38,7 +38,7 @@ import {approveFee, approveFeeFromAnyContract, getFeeInSkillFromUsd} from './con
import {raid as featureFlagRaid, stakeOnly as featureFlagStakeOnly, burningManager as featureFlagBurningManager} from './feature-flags';
import {IERC20, IERC721, INftStakingRewards, IStakingRewards} from '../../build/ab... | frontend/src/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | issue-1080-additional-changes | 1,121 | CryptoBlades/cryptoblades | 321 | Vue | kevinunger | |
this.loading = true;
try {
await this.approvePvpSkillSpending(this.reRollCost.toFixed(0));
await this.reRollOpponent(this.currentCharacterId);
} catch (err) {
console.log('reroll opponent error: ', err.message);
this.handleErrorMessage(err.message, 'No enemy found', ... | No issues found. | this.loading = true;
try {
await this.approvePvpSkillSpending(this.reRollCost.toFixed(0));
await this.reRollOpponent(this.currentCharacterId);
} catch (err) {
console.log('reroll opponent error: ', err.message);
this.handleErrorMessage(err.message, 'No enemy found', ... | @@ -176,6 +176,7 @@ import lightningIcon from '../../assets/elements/lightning.png';
import PvPDuelModal from './PvPDuelModal.vue';
import PvPUnderAttackModal from './PvPUnderAttackModal.vue';
import { duelResultFromContract as formatDuelResult } from '../../contract-models';
+import i18n from '../../i18n';
expor... | frontend/src/components/smart/PvPArenaMatchMaking.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Feat/pvp leave arena button | 1,150 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "abdk-libraries-solidity/ABDKMath64x64.sol";
library Common {
using ABDKMath64x64 for int128;
using SafeMath for uint256;
using SafeMath for uint8;
function isTraitEffectiveAgainst(uint8 attacker, uint8 defender) inter... | No issues found. | pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "abdk-libraries-solidity/ABDKMath64x64.sol";
library Common {
using ABDKMath64x64 for int128;
using SafeMath for uint256;
using SafeMath for uint8;
function isTraitEffectiveAgainst(uint8 attacker, uint8 defender) inter... | @@ -20,6 +20,14 @@ library Common {
return uint24(weaponMultiplier.mulu(basePower).add(bonusPower));
}
+ function getPlayerPowerBase100(
+ uint256 basePower,
+ int128 weaponMultiplier,
+ uint24 bonusPower
+ ) internal pure returns (uint24) {
+ // we divide total power b... | contracts/common.sol | 0 | Solidity | 1 | none | 16 | 46 | 46 | true | Feat/pvp base100 formula update | 1,189 | CryptoBlades/cryptoblades | 321 | Vue | Dvidaurre | |
async getOwnedLandIdsWithTier({state}) {
const CBKLand = state.contracts().CBKLand!;
if (!state.defaultAccount || !CBKLand) return;
const landsIds = await CBKLand.methods
.getOwned(state.defaultAccount)
.call(defaultCallOptions(state));
const landIdsWithTier ... | No issues found. | async getOwnedLandIdsWithTier({state}) {
const CBKLand = state.contracts().CBKLand!;
if (!state.defaultAccount || !CBKLand) return;
const landsIds = await CBKLand.methods
.getOwned(state.defaultAccount)
.call(defaultCallOptions(state));
const landIdsWithTier ... | @@ -5553,6 +5553,13 @@ export function createStore(web3: Web3) {
await dispatch('fetchCharacterPower', charId);
},
+ async transferSoul({ state }, {targetAddress, soulAmount}) {
+ const { BurningManager } = state.contracts();
+ if(!BurningManager || !state.defaultAccount) return;
+
... | frontend/src/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add UI for soul transfer | 1,236 | CryptoBlades/cryptoblades | 321 | Vue | brian-man | |
gasPrice: getGasPrice(),
});
await dispatch('fetchStakeDetails', { stakeType: 'king' });
},
async getStakedIds({ state }, stakeType) {
const { StakingRewards } = getStakingContracts(state.contracts(), stakeType);
const CBKLand = state.contracts().CBKLand!;
... | No issues found. | gasPrice: getGasPrice(),
});
await dispatch('fetchStakeDetails', { stakeType: 'king' });
},
async getStakedIds({ state }, stakeType) {
const { StakingRewards } = getStakingContracts(state.contracts(), stakeType);
const CBKLand = state.contracts().CBKLand!;
... | @@ -32,7 +32,7 @@ import {
StakeType
} from '@/interfaces';
import {getCharacterNameFromSeed} from '@/character-name';
-import {approveFee, approveFeeFromAnyContract, approveFeeFromAnyContractSimple, getFeeInSkillFromUsd} from '@/contract-call-utils';
+import {approveFee, approveFeeDynamic, approveFeeWalletOnly, a... | frontend/src/store/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Audit and fix approval logic in store.ts | 1,249 | CryptoBlades/cryptoblades | 321 | Vue | brian-man | |
const { upgradeProxy, deployProxy } = require('@openzeppelin/truffle-upgrades');
const PartnerGiveaways = artifacts.require('PartnerGiveaways');
const SpecialWeaponsManager = artifacts.require('SpecialWeaponsManager');
module.exports = async function (deployer, network) {
const specialWeaponsManager = await Special... | No issues found. | const { upgradeProxy, deployProxy } = require('@openzeppelin/truffle-upgrades');
const PartnerGiveaways = artifacts.require('PartnerGiveaways');
const SpecialWeaponsManager = artifacts.require('SpecialWeaponsManager');
module.exports = async function (deployer, network) {
const specialWeaponsManager = await Special... | @@ -0,0 +1,11 @@
+const { upgradeProxy, deployProxy } = require('@openzeppelin/truffle-upgrades');
+
+const PartnerGiveaways = artifacts.require('PartnerGiveaways');
+const SpecialWeaponsManager = artifacts.require('SpecialWeaponsManager');
+
+module.exports = async function (deployer, network) {
+ const specialWeapon... | migrations/143_partner_giveaway.js | 0 | JavaScript | 1 | none | 16 | 12 | 12 | true | Heco giveaway | 1,258 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
]),
async getPlayers(){
const tierTopRankersIds = await this.getTierTopCharacters(this.tierFilter);
this.tierTopRankers = await Promise.all(tierTopRankersIds.map(async (rankerId) => {
const rename = await this.getRename(rankerId);
return {
rankerId,
name: rename ... | No issues found. | ]),
async getPlayers(){
const tierTopRankersIds = await this.getTierTopCharacters(this.tierFilter);
this.tierTopRankers = await Promise.all(tierTopRankersIds.map(async (rankerId) => {
const rename = await this.getRename(rankerId);
return {
rankerId,
name: rename ... | @@ -56,16 +56,16 @@ export default {
return {
tierTopRankers: [],
tierFilterOptions: [
- { text: '1', value: 0 },
- { text: '2', value: 1 },
- { text: '3', value: 2 },
- { text: '4', value: 3 },
- { text: '5', value: 4 },
- { text: '6', value: 5 },
- {... | frontend/src/components/smart/PvPLeaderboards.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | fix leaderboards and error messages | 1,273 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
return await CBKLand.methods.updateChunkId(ids, chunkId).send({from: state.defaultAccount});
},
async incrementDustSupplies({state}, {playerAddress, amountLB, amount4B, amount5B}) {
const {Weapons} = state.contracts();
if(!state.defaultAccount || !Weapons) return;
return aw... | No issues found. | return await CBKLand.methods.updateChunkId(ids, chunkId).send({from: state.defaultAccount});
},
async incrementDustSupplies({state}, {playerAddress, amountLB, amount4B, amount5B}) {
const {Weapons} = state.contracts();
if(!state.defaultAccount || !Weapons) return;
return aw... | @@ -1905,8 +1905,9 @@ export function createStore(web3: Web3) {
commit('updateCharacterCosmetic', { characterId, characterCosmetic });
}
},
- async mintCharacter({ state, dispatch }) {
+ async mintCharacter({ state, dispatch }, approveMintSlippage: boolean) {
if(featureFlag... | frontend/src/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Dynamic mint prices | 1,292 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
this.handleErrorMessage(err.message, 'Char dueling', i18n.t('pvp.charDueling'));
this.handleErrorMessage(err.message, 'Not in arena', i18n.t('pvp.charNotInArena'));
this.loading = false;
return;
}
this.match = await this.getMatchByFinder(this.currentCharacterId);
thi... | No issues found. | this.handleErrorMessage(err.message, 'Char dueling', i18n.t('pvp.charDueling'));
this.handleErrorMessage(err.message, 'Not in arena', i18n.t('pvp.charNotInArena'));
this.loading = false;
return;
}
this.match = await this.getMatchByFinder(this.currentCharacterId);
thi... | @@ -27,14 +27,21 @@
<a tabindex="0" class="infoPopover" id="duel-popover">
<span>{{$t('pvp.battleOdds')}}</span>
<div v-if="opponentInformation.fullPower" class="icon">!</div>
- <b-popover v-if="opponentInformation.fullPower" ref="popover" target="duel-popover" triggers="hover blur" placement="bot... | frontend/src/components/smart/PvPArenaMatchMaking.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Feat/pvp withdrawal penalty | 1,293 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
hideWeapons: [],
useStakedForForge:false,
disableUseStakedForForge: false,
disableX10ForgeWithStaked: false,
forgeCostBN: new BN(0),
targetSkin: '',
haveWeaponCosmetic1: 0,
haveWeaponCosmetic2: 0,
selectedSpecialWeaponEventId: 0,
updateInterval: null as Return... | No issues found. | hideWeapons: [],
useStakedForForge:false,
disableUseStakedForForge: false,
disableX10ForgeWithStaked: false,
forgeCostBN: new BN(0),
targetSkin: '',
haveWeaponCosmetic1: 0,
haveWeaponCosmetic2: 0,
selectedSpecialWeaponEventId: 0,
updateInterval: null as Return... | @@ -1,8 +1,8 @@
<template>
<div class="body main-font">
- <b-tabs justified>
- <b-tab :title="$t('weapons')">
- <div class="blank-slate" v-if="ownWeapons.length === 0">
+ <b-row>
+ <b-col xl="12 weapon-body" v-if="$route.query.tab === 'weapon'">
+ <div class="blank-slate" v-if="ownWea... | frontend/src/views/Blacksmith.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | New game UI blacksmith sidebar | 1,310 | CryptoBlades/cryptoblades | 321 | Vue | Spintacle123 | |
this.ownCharacters.forEach(async (c) => {
await this.updateCharacterStamina(c.id);
});
this.ownGarrisonCharacters.forEach(async (c) => {
await this.updateCharacterStamina(c.id);
});
}, 3000);
this.availableStakeTypes.forEach((item) => {
this.fetchStakeDetails({ sta... | No issues found. | this.ownCharacters.forEach(async (c) => {
await this.updateCharacterStamina(c.id);
});
this.ownGarrisonCharacters.forEach(async (c) => {
await this.updateCharacterStamina(c.id);
});
}, 3000);
this.availableStakeTypes.forEach((item) => {
this.fetchStakeDetails({ sta... | @@ -1,5 +1,10 @@
<template>
<div class="app">
+ <Banner
+ text="GIVEAWAY: Win 1 of 10 Level 70+ Characters"
+ link="https://gleam.io/uswdy/cryptoblades-70-character-giveaway"
+ linkText="Enter here"
+ />
<nav-bar :isToggled="toggleSideBar"/>
<div class="content dark-bg-text">
<... | frontend/src/App.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | +promo banner | 1,329 | CryptoBlades/cryptoblades | 321 | Vue | kevinunger | |
const { deployProxy } = require("@openzeppelin/truffle-upgrades");
const CryptoBlades = artifacts.require("CryptoBlades");
const TokensManager = artifacts.require("TokensManager");
module.exports = async function (deployer, network, accounts) {
const game = await CryptoBlades.deployed();
if (
network... | No issues found. | const { deployProxy } = require("@openzeppelin/truffle-upgrades");
const CryptoBlades = artifacts.require("CryptoBlades");
const TokensManager = artifacts.require("TokensManager");
module.exports = async function (deployer, network, accounts) {
const game = await CryptoBlades.deployed();
if (
network... | @@ -0,0 +1,37 @@
+const { deployProxy } = require("@openzeppelin/truffle-upgrades");
+
+const CryptoBlades = artifacts.require("CryptoBlades");
+const TokensManager = artifacts.require("TokensManager");
+
+module.exports = async function (deployer, network, accounts) {
+ const game = await CryptoBlades.deployed();
+... | migrations/163_tokens_manager.js | 0 | JavaScript | 1 | none | 16 | 37 | 37 | true | Charge native token fee on combat | 1,349 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
function getBonusRankingPoints(uint256 weakerPower, uint256 strongerPower) internal pure returns (uint256) {
// @TODO once tested transform to save gas:
// X < Y: (1 - ( (1.3*(x-y)/0.6*y) + (0.7*(y-x)/0.6*x) )) * 0.5
// Note: Formula hard-copied in PvPArenaMatchMaking.vue due to contract si... | No issues found. | function getBonusRankingPoints(uint256 weakerPower, uint256 strongerPower) internal pure returns (uint256) {
// @TODO once tested transform to save gas:
// X < Y: (1 - ( (1.3*(x-y)/0.6*y) + (0.7*(y-x)/0.6*x) )) * 0.5
// Note: Formula hard-copied in PvPArenaMatchMaking.vue due to contract si... | @@ -82,4 +82,12 @@ library Common {
.mul(level.div(10).add(1))
);
}
+
+ function adjustDecimals(uint256 amount, uint256 decimals) internal pure returns (uint256 adjustedAmount){
+ if(decimals > 18) {
+ adjustedAmount = amount.mul(10**uint(decimals - 18));
+ } e... | contracts/common.sol | 0 | Solidity | 1 | none | 16 | 51 | 51 | true | Cb launchpad | 1,362 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
// Note: All prices are multiplied by 100
uint256 public tokenPrice;
uint256 public skillTokenPrice;
uint8 public offsetSlippage;
modifier restricted() {
_restricted();
_;
}
function _restricted() internal view {
require(hasRole(GAME_ADMIN, msg.sender));
}
... | No issues found. | // Note: All prices are multiplied by 100
uint256 public tokenPrice;
uint256 public skillTokenPrice;
uint8 public offsetSlippage;
modifier restricted() {
_restricted();
_;
}
function _restricted() internal view {
require(hasRole(GAME_ADMIN, msg.sender));
}
... | @@ -17,6 +17,7 @@ contract TokensManager is Initializable, AccessControlUpgradeable {
// Note: All prices are multiplied by 100
uint256 public tokenPrice;
uint256 public skillTokenPrice;
+ uint8 public offsetSlippage;
modifier restricted() {
_restricted();
@@ -35,6 +36,7 @@ contract To... | contracts/TokensManager.sol | 0 | Solidity | 1 | none | 16 | 51 | 51 | true | add slippage margin to offset | 1,380 | CryptoBlades/cryptoblades | 321 | Vue | Jcalcaldev | |
if(currency === 0) {
await approveFeeWalletOnly(
CryptoBlades,
SkillToken,
state.defaultAccount,
defaultCallOptions(state),
defaultCallOptions(state),
price
);
} else {
const tokenAddress = await Blacksmith.methods
... | No issues found. | if(currency === 0) {
await approveFeeWalletOnly(
CryptoBlades,
SkillToken,
state.defaultAccount,
defaultCallOptions(state),
defaultCallOptions(state),
price
);
} else {
const tokenAddress = await Blacksmith.methods
... | @@ -1032,6 +1032,15 @@ export default new Vuex.Store<IState>({
},
actions: {
+ async fetchIgoRewardsPerFight({ state }) {
+ const { CryptoBlades } = state.contracts();
+ if(!CryptoBlades || !state.defaultAccount) return;
+
+ const igoDefaultReward = await CryptoBlades.methods
+ .vars(27... | frontend/src/store/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | separate igo and unclaimed on fight rewards | 1,434 | CryptoBlades/cryptoblades | 321 | Vue | byyyyyyyyy | |
<g id="Polygon_1" data-name="Polygon 1" transform="translate(451.5 586.5) rotate(90)">
<path id="Path_20" data-name="Path 20" d="M26,0,52,47H0Z" fill="none"/>
<path id="Path_21" data-name="Path 21" d="M26,2.066,1.7,46H50.3L26,2.066M26,0,52,47H0Z" fill="#edcd90"/>
</g>
<g id="Polygon_2"... | No issues found. | <g id="Polygon_1" data-name="Polygon 1" transform="translate(451.5 586.5) rotate(90)">
<path id="Path_20" data-name="Path 20" d="M26,0,52,47H0Z" fill="none"/>
<path id="Path_21" data-name="Path 21" d="M26,2.066,1.7,46H50.3L26,2.066M26,0,52,47H0Z" fill="#edcd90"/>
</g>
<g id="Polygon_2"... | @@ -0,0 +1,117 @@
+<template>
+ <svg class="frame-card" xmlns="http://www.w3.org/2000/svg" width="466.717" height="602.694" viewBox="0 0 466.717 602.694">
+ <g id="frame2" transform="translate(-556.449 -285.501)">
+ <g id="Group_7" data-name="Group 7" transform="translate(154 -23.94)">
+ <g id="Group_2" data-... | frontend/src/components/CardFrameToggled.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Fixed Some issues in ui | 1,446 | CryptoBlades/cryptoblades | 321 | Vue | Spintacle123 | |
return this.ownedGarrisonCharacterIds.includes(this.currentCharacterId)
? this.characterStaminas[this.currentCharacterId]
: this.timestampToStamina(this.characters[this.currentCharacterId]?.staminaTimestamp ?? 0);
},
characterExp(): number {
return this.characters[this.currentCharact... | No issues found. | return this.ownedGarrisonCharacterIds.includes(this.currentCharacterId)
? this.characterStaminas[this.currentCharacterId]
: this.timestampToStamina(this.characters[this.currentCharacterId]?.staminaTimestamp ?? 0);
},
characterExp(): number {
return this.characters[this.currentCharact... | @@ -93,14 +93,16 @@
<b-tabs pills fill nav-wrapper-class="mt-5 mb-4" >
<upgrade-tab :soulBalance="soulBalance" @fetchSoulBalance="refreshData" />
<skins-tab :availableSkins="availableSkins" @loadCosmeticsCount="loadCosmeticsCount" />
- <options-tab @openTransferModal="openTransfe... | frontend/src/components/smart/Character.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | New game UI soul transfer | 1,454 | CryptoBlades/cryptoblades | 321 | Vue | byyyyyyyyy | |
ttHtml += `<br>5B: ${this.weapon.fiveStarBurnPoints}/10`;
}
if(this.weapon.bonusPower > 0) {
ttHtml += `<br>${this.$t('weaponIcon.bonusPower')} ${this.weapon.bonusPower}`;
}
return ttHtml;
}
},
data() {
return {
hover: false,
allLoaded: false,
all... | No issues found. | ttHtml += `<br>5B: ${this.weapon.fiveStarBurnPoints}/10`;
}
if(this.weapon.bonusPower > 0) {
ttHtml += `<br>${this.$t('weaponIcon.bonusPower')} ${this.weapon.bonusPower}`;
}
return ttHtml;
}
},
data() {
return {
hover: false,
allLoaded: false,
all... | @@ -78,12 +78,12 @@
<!-- raid selected weapon display (DESKTOP VIEW)-->
<div v-if="displayType === 'raid'" class="glow-container" ref="el">
<div class="weapon-flex">
- <div :class="'weapon-img-desktop frame-'+ (weapon.stars || 0)" style="border-radius:5px">
+ <div :class="'weapon-img-des... | frontend/src/components/WeaponInvetory.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | UI bug fixes 02 | 1,476 | CryptoBlades/cryptoblades | 321 | Vue | Spintacle123 | |
margin: auto;
width: 400px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.info{
font-family: Roboto;
color: rgba(255, 255, 255, 0.658);
font-size: 13px !important;
margin-bottom: 20px;
}
.reforge-bonus{
margin-top: 20px;
text-align: left !important;
}
... | No issues found. | margin: auto;
width: 400px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.info{
font-family: Roboto;
color: rgba(255, 255, 255, 0.658);
font-size: 13px !important;
margin-bottom: 20px;
}
.reforge-bonus{
margin-top: 20px;
text-align: left !important;
}
... | @@ -150,12 +150,14 @@
:disableX10Forge="disableX10Forge"
:disableX10ForgeWithStaked="disableX10ForgeWithStaked"
:disableUseStakedForForge="disableUseStakedForForge"
+ :canClaim="canClaim"
@onClickForge="onClickForge"
@onClickSpecialForge="onClickSpecialForge"
... | frontend/src/views/Blacksmith.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | SafeRandoms in shields and weapons minting | 1,578 | CryptoBlades/cryptoblades | 321 | Vue | Chriserus | |
margin-right: -10px;
}
}
.set-normal{
margin-left: auto;
margin-right: auto;
transition: 1s width;
padding: 0px;
width: auto;
overflow-x: clip;
}
hr.hr-divider {
border-top: 1px solid #9e8a57;
margin-bottom: 0.5rem !important;
}
html, body {
margin: 0;
height: 100%;
width: 100%;
backgrou... | No issues found. | margin-right: -10px;
}
}
.set-normal{
margin-left: auto;
margin-right: auto;
transition: 1s width;
padding: 0px;
width: auto;
overflow-x: clip;
}
hr.hr-divider {
border-top: 1px solid #9e8a57;
margin-bottom: 0.5rem !important;
}
html, body {
margin: 0;
height: 100%;
width: 100%;
backgrou... | @@ -539,23 +539,43 @@ button.btn.button.main-font.dark-bg-text.encounter-button.btn-styled.btn-primary
}
.app{
- width: auto;
+ width: 100%;
+ display: flex;
+ flex-flow: column;
+ height: 100%;
+ overflow: auto;
}
+.app .content.bg-dark{
+ flex: 1;
+}
+
+@media all and (max-width: 767.98px) {
+ div.cont... | frontend/src/App.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Background does not fit height | 1,607 | CryptoBlades/cryptoblades | 321 | Vue | jakehein | |
justify-content: center;
-ms-transform: rotate(-45deg); /* IE 9 */
transform: rotate(-45deg);
}
.element-frame-active div{
opacity: 0;
}
div.character-list{
width: 70%;
}
.character-list{
padding-top: 20px;
overflow-x:hidden;
overflow-y: visible;
}
.raid-indicator{
content: url('../../assets/navb... | No issues found. | justify-content: center;
-ms-transform: rotate(-45deg); /* IE 9 */
transform: rotate(-45deg);
}
.element-frame-active div{
opacity: 0;
}
div.character-list{
width: 70%;
}
.character-list{
padding-top: 20px;
overflow-x:hidden;
overflow-y: visible;
}
.raid-indicator{
content: url('../../assets/navb... | @@ -73,6 +73,9 @@
</div>
</b-col>
</div>
+ <div class="d-flex justify-content-center" v-if="currentPath != '/blacksmith'">
+ <EarningsCalculator />
+ </div>
<div class="btn-trigger" @click="hideSideBar(!toggled)">
<img :class="!toggled ? 'rot... | frontend/src/components/smart/CharacterDisplay.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Earnings calc | 1,612 | CryptoBlades/cryptoblades | 321 | Vue | kcper | |
.getCharacterCosmetic(characterId)
.call(defaultCallOptions(state));
if(state.characterCosmetics[characterId] !== characterCosmetic){
commit('updateCharacterCosmetic', { characterId, characterCosmetic });
}
},
async mintCharacter({ state, dispatch }, approveMintSlippage: bool... | No issues found. | .getCharacterCosmetic(characterId)
.call(defaultCallOptions(state));
if(state.characterCosmetics[characterId] !== characterCosmetic){
commit('updateCharacterCosmetic', { characterId, characterCosmetic });
}
},
async mintCharacter({ state, dispatch }, approveMintSlippage: bool... | @@ -753,9 +753,9 @@ export default new Vuex.Store<IState>({
subscriptions.push(
Characters.events.NewCharacter(
{ filter: { minter: state.defaultAccount } },
- async (err: Error, data: any) => {
- if (err) {
- console.error(err, data);
+ async (error:... | frontend/src/store/store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix refreshes after joining raid, unselect weapon | 1,634 | CryptoBlades/cryptoblades | 321 | Vue | Chriserus | |
interface StoreMappedActions {
userHasDefaultAdminAccess(payload: { contract: Contract<any> }): Promise<boolean>;
userHasGameAdminAccess(payload: { contract: Contract<any> }): Promise<boolean>;
userHasMinterAccess(payload: { contract: Contract<any> }): Promise<boolean>;
}
interface Data {
hasTabAccess: bool... | No issues found. |
interface StoreMappedActions {
userHasDefaultAdminAccess(payload: { contract: Contract<any> }): Promise<boolean>;
userHasGameAdminAccess(payload: { contract: Contract<any> }): Promise<boolean>;
userHasMinterAccess(payload: { contract: Contract<any> }): Promise<boolean>;
}
interface Data {
hasTabAccess: bool... | @@ -40,6 +40,7 @@ import BlacksmithAdmin from './AdminTabs/BlacksmithAdmin.vue';
import RaidAdmin from './AdminTabs/RaidAdmin.vue';
import SpecialWeaponsManagerAdmin from './AdminTabs/SpecialWeaponsManagerAdmin.vue';
import DexAdmin from './AdminTabs/DexAdmin.vue';
+import SkillAdmin from './AdminTabs/SkillAdmin.vue... | frontend/src/components/smart/AdminTab.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | Able to transfer skill from deployer wallet to skill | 1,890 | CryptoBlades/cryptoblades | 321 | Vue | jeffyzxc | |
const web3 = new Web3();
const randomSignerWallet = Wallet.createRandom();
const randomSignerPrivatekey = randomSignerWallet.privateKey;
const randomSignerAddress = randomSignerWallet.address;
const nonce = new BN(0);
const gas = new BN(100000);
const gasPrice: string = await mineGasForTransaction(web... | No issues found. | const web3 = new Web3();
const randomSignerWallet = Wallet.createRandom();
const randomSignerPrivatekey = randomSignerWallet.privateKey;
const randomSignerAddress = randomSignerWallet.address;
const nonce = new BN(0);
const gas = new BN(100000);
const gasPrice: string = await mineGasForTransaction(web... | @@ -0,0 +1,73 @@
+import PowChains from '../config/pow.json';
+import Web3 from 'web3';
+import { Wallet } from '@ethersproject/wallet';
+import BN from 'bn.js';
+import mineGasForTransaction from './miner';
+
+interface Params {
+ account: string;
+ network: 'mainnet';
+}
+
+export async function userProofOfWork(par... | frontend/src/utils/pow.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Added ability to mint sfuel | 1,897 | CryptoBlades/cryptoblades | 321 | Vue | jeffyzxc | |
res.transactionHash
);
const bnbGasUsed = gasUsedToBnb(res.gasUsed, gasPrice);
await Promise.all([dispatch('combat/fetchTargets', { characterId })]);
return {
isVictory: parseInt(playerRoll, 10) >= parseInt(enemyRoll, 10),
playerRoll,
enemyRoll,
xpGain,
... | No issues found. | res.transactionHash
);
const bnbGasUsed = gasUsedToBnb(res.gasUsed, gasPrice);
await Promise.all([dispatch('combat/fetchTargets', { characterId })]);
return {
isVictory: parseInt(playerRoll, 10) >= parseInt(enemyRoll, 10),
playerRoll,
enemyRoll,
xpGain,
... | @@ -150,12 +150,13 @@ const combat = {
if (!TokensManager || !CryptoBlades || !rootState.defaultAccount) return;
const res = await TokensManager.methods
- .fight(
- characterId,
- targetString,
- fightMultiplier
- )
- .send({ from: rootState.defaultAccount... | frontend/src/store/combat/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Solving issue #1905: Aggregate Fights into a single txn to reduce gas… | 1,906 | CryptoBlades/cryptoblades | 321 | Vue | NindoK | |
cmd = fmt.Sprintf("INCR key")
value := fireCommand(conn, cmd)
if value.(int64) != 2 {
t.Fail()
}
fireCommand(conn, "ABORT")
wg.Wait()
}
func TestINCRWhenKeyDoesNotExist(t *testing.T) {
var wg sync.WaitGroup
go runTestServer(&wg)
conn := getLocalConnection()
cmd := fmt.Sprintf("INCR key")
value := fi... | 1. You can merge all of these test cases in a single unit test.
2. Refer to https://github.com/DiceDB/dice/blob/master/core/bytelist_test.go. It will suggest how to write tests in Go. | go runTestServer(&wg)
conn := getLocalConnection()
for _, tc := range []tcase{
{"s", "key1", 0},
{"i", "key1", 1},
{"i", "key1", 2},
{"i", "key2", 1},
{"g", "key1", 2},
{"g", "key2", 1},
} {
switch tc.op[0] {
case 's':
cmd := fmt.Sprintf("SET %s %d", tc.key, tc.val)
fireCommand(conn, cmd)
... | @@ -0,0 +1,70 @@
+package tests
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+)
+
+func TestINCRWhenKeyAlreadyExists(t *testing.T) {
+ var wg sync.WaitGroup
+ go runTestServer(&wg)
+
+ conn := getLocalConnection()
+
+ cmd := fmt.Sprintf("SET key %s", "1")
+ fireCommand(conn, cmd)
+
+ cmd = fmt.Sprintf("INCR key")
+
+ value... | tests/incr_test.go | 26 | Go | 0.357 | suggestion | 184 | 51 | 37 | false | Add the test cases for INCR commmand | 97 | DiceDB/dice | 10,326 | C | arpitbbhayani | FuncGuy |
package tests
import (
"fmt"
"sync"
"testing"
)
type tcase struct {
op string
val int64
}
func TestINCR(t *testing.T) {
var wg sync.WaitGroup
go runTestServer(&wg)
conn := getLocalConnection()
for _, tc := range []tcase{
{"s1", 0},
{"i1", 1},
{"i1", 1},
} {
switch tc.op[0] {
case 's':
cmd :... | why `s1` and `i1`, you would have used `s` and `i` itself. | package tests
import (
"fmt"
"strconv"
"sync"
"testing"
)
type tcase struct {
op string
key string
val int64
}
func TestINCR(t *testing.T) {
var wg sync.WaitGroup
go runTestServer(&wg)
conn := getLocalConnection()
for _, tc := range []tcase{
{"s", "key1", 0},
{"i", "key1", 1},
{"i", "key1", 2},
... | @@ -0,0 +1,43 @@
+package tests
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+)
+
+type tcase struct {
+ op string
+ val int64
+}
+
+func TestINCR(t *testing.T) {
+ var wg sync.WaitGroup
+ go runTestServer(&wg)
+ conn := getLocalConnection()
+
+ for _, tc := range []tcase{
+ {"s1", 0},
+ {"i1", 1},
+ {"i1", 1}, | tests/incr_test.go | 22 | Go | 0.429 | suggestion | 58 | 44 | 47 | false | Add the test cases for INCR commmand | 97 | DiceDB/dice | 10,326 | C | arpitbbhayani | FuncGuy |
op string
key string
val int64
}
func TestINCR(t *testing.T) {
var wg sync.WaitGroup
go runTestServer(&wg)
conn := getLocalConnection()
for _, tc := range []tcase{
{"s", "key1", 0},
{"i", "key1", 1},
{"i", "key1", 1},
{"i", "key2", 1},
} {
switch tc.op[0] {
case 's':
cmd := fmt.Sprintf("SET %... | This for loop is supposed to hold the test cases. You have only written the operations to be done and are checking the correctness at the end. This is not how unittests are written please go through other tests written in the codebase. | type tcase struct {
op string
key string
val int64
}
func TestINCR(t *testing.T) {
var wg sync.WaitGroup
go runTestServer(&wg)
conn := getLocalConnection()
for _, tc := range []tcase{
{"s", "key1", 0},
{"i", "key1", 1},
{"i", "key1", 2},
{"i", "key2", 1},
{"g", "key1", 2},
{"g", "key2", 1},
} {
... | @@ -0,0 +1,55 @@
+package tests
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+)
+
+type tcase struct {
+ op string
+ key string
+ val int64
+}
+
+func TestINCR(t *testing.T) {
+ var wg sync.WaitGroup
+ go runTestServer(&wg)
+ conn := getLocalConnection()
+
+ for _, tc := range []tcase{
+ {"s", "key1", 0},
+ {"i", "key1"... | tests/incr_test.go | 26 | Go | 0.429 | suggestion | 235 | 47 | 45 | false | Add the test cases for INCR commmand | 97 | DiceDB/dice | 10,326 | C | arpitbbhayani | FuncGuy |
if WatchList[key] == nil {
WatchList[key] = make(map[int]struct{})
}
// Add the client to this key's watch list
WatchList[key][c.Fd] = struct{}{}
return RESP_OK
}
// evalUNQWATCH removes the caller's file descriptor from the watch list of the specified key.
func evalUNQWATCH(args []string, c *Client) []byte {... | nitpick: If we don't want this, let's remove this instead of commenting. | if WatchList[query] == nil {
WatchList[query] = make(map[int]struct{})
}
// Add the client to this key's watch list
WatchList[query][c.Fd] = struct{}{}
return RESP_OK
}
// evalUNQWATCH removes the caller's file descriptor from the watch list of the specified key.
func evalUNQWATCH(args []string, c *Client) []... | @@ -825,40 +825,40 @@ func evalQWATCH(args []string, c *Client) []byte {
}
// Parse and get the selection from the query.
- key, error := ParseQuery( /*sql=*/ args[0])
+ query, error := ParseQuery( /*sql=*/ args[0])
if error != nil {
return Encode(error, false)
}
WatchListMutex.Lock()
defer WatchLi... | core/eval.go | 26 | Go | 0.286 | refactor | 72 | 51 | 51 | false | Supporting wildcard FROM, ORDER BY $value and LIMIT in DSQL | 124 | DiceDB/dice | 10,326 | C | arpitbbhayani | JyotinderSingh |
package tests
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCOUNT(t *testing.T) {
commandsCount := 40
subscriber := getLocalConnection()
responseValue := fireCommand(subscriber, "COUNT")
responseCount := responseValue.(int64)
if responseValue == nil {
t.Fail()
}
assert.Assert(t,... | Why call this subscriber? This is just a simple local TCP connection, so name it `connection` at best. | package tests
import (
"fmt"
"gotest.tools/v3/assert"
"net"
"testing"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
commandCount := getCommandCount(connection)
if commandCount <= 0 {
t.Fail()
}
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of CLI commands ... | @@ -0,0 +1,41 @@
+package tests
+
+import (
+ "fmt"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCOUNT(t *testing.T) {
+ commandsCount := 40
+
+ subscriber := getLocalConnection() | tests/command_count_test.go | 13 | Go | 0.5 | question | 102 | 38 | 37 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | arpitbbhayani | VipinRaiP |
package tests
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCOUNT(t *testing.T) {
commandsCount := 40
subscriber := getLocalConnection()
responseValue := fireCommand(subscriber, "COUNT")
responseCount := responseValue.(int64)
if responseValue == nil {
t.Fail()
}
assert.Assert(t,... | instead of typecasting this to `int64` you can set commandCount as `int64` while declaring. Also, is this a good idea to test this? So, every time you add a new command, this test is bound to fail. Can you confirm how is Redis codebase testing this? | package tests
import (
"fmt"
"gotest.tools/v3/assert"
"net"
"testing"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
commandCount := getCommandCount(connection)
if commandCount <= 0 {
t.Fail()
}
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of CLI commands ... | @@ -0,0 +1,41 @@
+package tests
+
+import (
+ "fmt"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCOUNT(t *testing.T) {
+ commandsCount := 40
+
+ subscriber := getLocalConnection()
+
+ responseValue := fireCommand(subscriber, "COUNT")
+ responseCount := responseValue.(int64)
+ if responseValue == nil ... | tests/command_count_test.go | 21 | Go | 0.786 | bug | 249 | 41 | 37 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | arpitbbhayani | VipinRaiP |
package tests
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCOUNT(t *testing.T) {
commandsCount := 40
subscriber := getLocalConnection()
responseValue := fireCommand(subscriber, "COUNT")
responseCount := responseValue.(int64)
if responseValue == nil {
t.Fail()
}
assert.Assert(t,... | Giving such generic function name is a really bad idea as this function is available throughout the package. Please reer to other benchmark functions and go's best practices and structure this better.
Also, update the output of number of allocs and time taken during the benchmar. | package tests
import (
"fmt"
"gotest.tools/v3/assert"
"net"
"testing"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
commandCount := getCommandCount(connection)
if commandCount <= 0 {
t.Fail()
}
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of CLI commands ... | @@ -0,0 +1,41 @@
+package tests
+
+import (
+ "fmt"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCOUNT(t *testing.T) {
+ commandsCount := 40
+
+ subscriber := getLocalConnection()
+
+ responseValue := fireCommand(subscriber, "COUNT")
+ responseCount := responseValue.(int64)
+ if responseValue == nil ... | tests/command_count_test.go | 25 | Go | 0.5 | suggestion | 283 | 41 | 37 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | arpitbbhayani | VipinRaiP |
func TestCommandCOUNT(t *testing.T) {
commandsCount := 40
subscriber := getLocalConnection()
responseValue := fireCommand(subscriber, "COUNT")
responseCount := responseValue.(int64)
if responseValue == nil {
t.Fail()
}
assert.Assert(t, responseCount == int64(commandsCount),
fmt.Sprintf("Unexpected numbe... | What is the purpose of passing `200` or `2000` here? Should it just keep firing the `COMMAND COUNT` command, essentially not needing the inner for loop?
Also, the name of the command is `COMMAND COUNT` and not `COUNT`. Please go through the Redis documentation linkedin the issue description. |
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
commandCount := getCommandCount(connection)
if commandCount <= 0 {
t.Fail()
}
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of CLI commands found. expected greater than 0, %d found", commandCount))
}
func getCommandC... | @@ -0,0 +1,41 @@
+package tests
+
+import (
+ "fmt"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCOUNT(t *testing.T) {
+ commandsCount := 40
+
+ subscriber := getLocalConnection()
+
+ responseValue := fireCommand(subscriber, "COUNT")
+ responseCount := responseValue.(int64)
+ if responseValue == nil ... | tests/command_count_test.go | 26 | Go | 0.643 | question | 295 | 33 | 29 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | arpitbbhayani | VipinRaiP |
package tests
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
responseValue := fireCommand(connection, "COMMAND COUNT")
responseCount := responseValue.(int64)
if responseValue == nil {
t.Fail()
}
assert.Assert(t, responseCount >... | Is it a good idea to include connection establishment as a part of the benchmark code? Maybe the connection should be created once in the caller and be reused across function calls for the benchmark. | package tests
import (
"fmt"
"gotest.tools/v3/assert"
"net"
"testing"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
commandCount := getCommandCount(connection)
if commandCount <= 0 {
t.Fail()
}
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of CLI commands ... | @@ -0,0 +1,34 @@
+package tests
+
+import (
+ "fmt"
+ "testing"
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCount(t *testing.T) {
+ connection := getLocalConnection()
+ responseValue := fireCommand(connection, "COMMAND COUNT")
+ responseCount := responseValue.(int64)
+ if responseValue == nil {
+ t.Fail()
+ }
+
... | tests/command_count_test.go | 22 | Go | 0.429 | suggestion | 199 | 34 | 37 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
package tests
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
responseValue := fireCommand(connection, "COMMAND COUNT")
responseCount := responseValue.(int64)
if responseValue == nil {
t.Fail()
}
assert.Assert(t, responseCount >... | This function can probably be reused for the TestCommandCount method as well. | package tests
import (
"fmt"
"gotest.tools/v3/assert"
"net"
"testing"
)
func TestCommandCount(t *testing.T) {
connection := getLocalConnection()
commandCount := getCommandCount(connection)
if commandCount <= 0 {
t.Fail()
}
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of CLI commands ... | @@ -0,0 +1,34 @@
+package tests
+
+import (
+ "fmt"
+ "testing"
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCount(t *testing.T) {
+ connection := getLocalConnection()
+ responseValue := fireCommand(connection, "COMMAND COUNT")
+ responseCount := responseValue.(int64)
+ if responseValue == nil {
+ t.Fail()
+ }
+
... | tests/command_count_test.go | 21 | Go | 0.286 | suggestion | 77 | 34 | 37 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
QREFREM = "QREFREM"
QREFLEN = "QREFLEN"
QREFPEEK = "QREFPEEK"
STACKINTPUSH = "STACKINTPUSH"
STACKINTPOP = "STACKINTPOP"
STACKINTLEN = "STACKINTLEN"
STACKINTPEEK = "STACKINTPEEK"
STACKREFPUSH = "STACKREFPUSH"
STACKREFPOP = "STACKREFPOP"
STACKREFLEN = "STACKREFLEN"
STACKREFPEEK = "STACKREFPEE... | Let's instead create a fixed-size array instead of a slice since it will never grow at runtime. |
return b
}
// evalSET puts a new <key, value> pair in db as in the args
// args must contain key and value.
// args can also contain multiple options -
//
// EX or ex which will set the expiry time(in secs) for the key
//
// Returns encoded error response if at least a <key, value> pair is not part of args
// Return... | @@ -21,11 +21,63 @@ var RESP_MINUS_1 []byte = []byte(":-1\r\n")
var RESP_MINUS_2 []byte = []byte(":-2\r\n")
var RESP_EMPTY_ARRAY []byte = []byte("*0\r\n")
+// All supported Dice Commands
+const (
+ PING = "PING"
+ SET = "SET"
+ GET = "GET"
+ TTL = "TTL"
+ DEL = "DEL"
+ EX... | core/eval.go | 26 | Go | 0.286 | suggestion | 95 | 51 | 51 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
}
// Add the client to this key's watch list
WatchList[query][c.Fd] = struct{}{}
return RESP_OK
}
// evalCOMMAND evaluates COMMAND <subcommand> command based on subcommand
// COUNT: return total count of commands in Dice.
func evalCOMMAND(args []string) []byte {
if len(args) == 0 {
return Encode(fmt.Errorf("(... | instead of calculating the length of the commands for every request, we can simply store it in a constant and return that. We can add a runtime check to verify that the constant's value does not get outdated.
```go
const (
diceCommandsCount = len(diceCommands)
)
func init() {
if len(diceCommands) != dic... |
return diceCmd.Eval(cmd.Args)
}
func executeCommandToBuffer(cmd *RedisCmd, buf *bytes.Buffer, c *Client) {
buf.Write(executeCommand(cmd, c))
}
func EvalAndRespond(cmds RedisCmds, c *Client) {
var response []byte
buf := bytes.NewBuffer(response)
for _, cmd := range cmds {
// if txn is not in progress, then we... | @@ -863,95 +915,117 @@ func evalQWATCH(args []string, c *Client) []byte {
return RESP_OK
}
+// evalCOMMAND evaluates COMMAND <subcommand> command based on subcommand
+// COUNT: return total count of commands in Dice.
+func evalCOMMAND(args []string) []byte {
+ if len(args) == 0 {
+ return Encode(fmt.Errorf("(erro... | core/eval.go | 26 | Go | 0.857 | suggestion | 406 | 51 | 39 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
}
if err := assertEncoding(obj.TypeEncoding, OBJ_ENCODING_QREF); err != nil {
return Encode(err, false)
}
q := obj.Value.(*QueueRef)
return Encode(q.Iterate(int(num)), false)
}
// evalSTACKREFPEEK peeks into the STACKREF and returns 5 elements without popping them
// returns the array of resp encoded values a... | nit: we could use errors.New() instead of fmt.Errorf().
There's not much difference, but since there are no custom args for this string we probably don't need fmt.Errorf | if len(args) != 1 {
return Encode(errors.New("ERR invalid number of arguments for `QWATCH` command (expected 1)"), false)
}
// Parse and get the selection from the query.
query, error := ParseQuery( /*sql=*/ args[0])
if error != nil {
return Encode(error, false)
}
AddWatcher(query, c.Fd)
return RESP_OK
... | @@ -863,95 +915,117 @@ func evalQWATCH(args []string, c *Client) []byte {
return RESP_OK
}
+// evalCOMMAND evaluates COMMAND <subcommand> command based on subcommand
+// COUNT: return total count of commands in Dice.
+func evalCOMMAND(args []string) []byte {
+ if len(args) == 0 {
+ return Encode(fmt.Errorf("(erro... | core/eval.go | 26 | Go | 0.571 | suggestion | 172 | 51 | 51 | false | #145 : Added support for COMMAND COUNT command | 153 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
}
}
func TestWildCardMatch(t *testing.T){
tests := []struct{
pattern string
key string
want bool
}{
{"a*b*c", "axybzxc", true},
{"", "", true},
{"abc", "abc", true},
{"a?c", "abc", true},
{"ac?", "abc", false},
{"ab?", "abc", true},
{"?bc", "xbc", true},
{"a*c", "abbbbbbc", true},
{"abc*", ... | We should probably use the same test cases for testing both the new and the old method. | }
func BenchmarkWildCardMatch(b *testing.B) {
testCases := []struct {
pattern string
key string
}{
{"*", "anystringwillmatch"},
{"?????", "exact"},
{"a?c*d", "abcdefgd"},
{"*test*", "thisIsATestString"},
{"???*", "abcdefghijklmnop"},
{"*a*b*c*", "111a222b333c444"},
{"a?b*c??d", "acb123cxxd"},
... | @@ -50,3 +50,37 @@ func TestRegexMatch(t *testing.T) {
})
}
}
+
+func TestWildCardMatch(t *testing.T){
+ tests := []struct{
+ pattern string
+ key string
+ want bool
+ }{
+ {"a*b*c", "axybzxc", true},
+ {"", "", true},
+ {"abc", "abc", true},
+ {"a?c", "abc", true},
+ {"ac?", "abc", false},
+ {"ab?", "a... | core/regex_test.go | 26 | Go | 0.286 | suggestion | 87 | 37 | 27 | false | Added wildcard matching for DSQL query | 169 | DiceDB/dice | 10,326 | C | JyotinderSingh | Dev79844 |
package core_test
import (
"testing"
"github.com/dicedb/dice/core"
)
func TestRegexMatch(t *testing.T) {
tests := []struct {
pattern string
key string
match bool
}{
{"*", "anything", true},
{"*", "", true},
{"?", "a", true},
{"?", "", false},
{"a?", "ab", true},
{"a?", "a", false},
{"a*... | Please include a benchmark to compare the performance of the new and the old code. This will help us understand if the new implementation is providing a speed-up.
Also, it's a good idea to include slightly more complicated wildcard test cases for the benchmark.
Once that is added, please include a screenshot of t... | package core_test
import (
"testing"
"github.com/dicedb/dice/core"
)
func TestWildCardMatch(t *testing.T){
tests := []struct{
pattern string
key string
want bool
}{
{"*", "anything", true},
{"*", "", true},
{"?", "a", true},
{"?", "", false},
{"a?", "ab", true},
{"a?", "a", false},
{"a*", "a... | core/regex_test.go | 1 | Go | 0.571 | performance | 373 | 26 | 26 | false | Added wildcard matching for DSQL query | 169 | DiceDB/dice | 10,326 | C | JyotinderSingh | Dev79844 | |
package core
type DiceCmdMeta struct {
Name string
Info string
Docs string
Eval func([]string) []byte
}
var (
diceCmds = map[string]DiceCmdMeta{}
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: "ping command info here",
Docs: "ping command docs here",
Eval: evalPING,
}
setCmdMeta = DiceCmdMeta{
Name... | The Eval functions already have the docs in code comments. Can we add them here for completeness? | package core
type DiceCmdMeta struct {
Name string
Info string
Eval func([]string) []byte
}
var (
diceCmds = map[string]DiceCmdMeta{}
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: `PING returns with an encoded "PONG" If any message is added with the ping command,the message will be returned.`,
Eval: eval... | @@ -0,0 +1,297 @@
+package core
+
+type DiceCmdMeta struct {
+ Name string
+ Info string
+ Docs string
+ Eval func([]string) []byte
+}
+
+var (
+ diceCmds = map[string]DiceCmdMeta{}
+
+ pingCmdMeta = DiceCmdMeta{
+ Name: "PING",
+ Info: "ping command info here", | core/commands.go | 15 | Go | 0.214 | question | 97 | 40 | 40 | false | #182: Refactor command handling for maintainability | 170 | DiceDB/dice | 10,326 | C | yashs360 | kakdeykaushik |
type DiceCmdMeta struct {
Name string
Info string
Docs string
Eval func([]string) []byte
}
var (
diceCmds = map[string]DiceCmdMeta{}
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: "ping command info here",
Docs: "ping command docs here",
Eval: evalPING,
}
setCmdMeta = DiceCmdMeta{
Name: "SET",
Inf... | Assuming Docs is a link to documentation -
We don't have a docs portal yet. Should we skip this atm? Any placeholders that we won't address in short term is smell for me.
Its easy enough to add it later in one go for all once we do something for docs. | type DiceCmdMeta struct {
Name string
Info string
Eval func([]string) []byte
}
var (
diceCmds = map[string]DiceCmdMeta{}
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: `PING returns with an encoded "PONG" If any message is added with the ping command,the message will be returned.`,
Eval: evalPING,
}
setC... | @@ -0,0 +1,297 @@
+package core
+
+type DiceCmdMeta struct {
+ Name string
+ Info string
+ Docs string
+ Eval func([]string) []byte
+}
+
+var (
+ diceCmds = map[string]DiceCmdMeta{}
+
+ pingCmdMeta = DiceCmdMeta{
+ Name: "PING",
+ Info: "ping command info here",
+ Docs: "ping command docs here",
+ Eval: evalPING,
+... | core/commands.go | 26 | Go | 0.5 | suggestion | 254 | 51 | 51 | false | #182: Refactor command handling for maintainability | 170 | DiceDB/dice | 10,326 | C | yashs360 | kakdeykaushik |
package core
import (
"fmt"
"log"
"sync"
"time"
"github.com/dicedb/dice/config"
"golang.org/x/crypto/bcrypt"
)
const (
DefaultUserName = "default"
AuthCmd = "AUTH"
SessionStatusPending SessionStatusT = SessionStatusT(0)
SessionStatusActive SessionStatusT = SessionStatusT(1)
SessionStatusExpired ... | Redis must be storing the users in some durable storage, or is everything transient? | package core
import (
"fmt"
"log"
"sync"
"time"
"github.com/dicedb/dice/config"
"golang.org/x/crypto/bcrypt"
)
const (
DefaultUserName = "default"
AuthCmd = "AUTH"
SessionStatusPending SessionStatusT = SessionStatusT(0)
SessionStatusActive SessionStatusT = SessionStatusT(1)
SessionStatusExpired ... | @@ -0,0 +1,154 @@
+package core
+
+import (
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/dicedb/dice/config"
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ DefaultUserName = "default"
+ AuthCmd = "AUTH"
+
+ SessionStatusPending SessionStatusT = SessionStatusT(0)
+ SessionStatusActive SessionStatusT = Sess... | core/session.go | 24 | Go | 0.286 | question | 84 | 49 | 49 | false | Add support for Basic Auth | 179 | DiceDB/dice | 10,326 | C | arpitbbhayani | gsarmaonline |
type (
SessionStatusT uint8
Session struct {
ID uint64
User *User
CreatedAt time.Time
LastAccessedAt time.Time
Status SessionStatusT
}
Users struct {
store map[string]*User
stLock *sync.RWMutex
}
User struct {
Username string
Passwords []string
IsPasswordEn... | Call this function `NewUserStore` |
type (
SessionStatusT uint8
Session struct {
ID uint64
User *User
CreatedAt time.Time
LastAccessedAt time.Time
Status SessionStatusT
}
Users struct {
store map[string]*User
stLock *sync.RWMutex
}
User struct {
Username string
Passwords []string
IsPasswordEn... | @@ -0,0 +1,154 @@
+package core
+
+import (
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/dicedb/dice/config"
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ DefaultUserName = "default"
+ AuthCmd = "AUTH"
+
+ SessionStatusPending SessionStatusT = SessionStatusT(0)
+ SessionStatusActive SessionStatusT = Sess... | core/session.go | 26 | Go | 0.286 | suggestion | 33 | 51 | 51 | false | Add support for Basic Auth | 179 | DiceDB/dice | 10,326 | C | arpitbbhayani | gsarmaonline |
)
var (
UserStore *Users = NewUsers()
)
type (
SessionStatusT uint8
Session struct {
ID uint64
User *User
CreatedAt time.Time
LastAccessedAt time.Time
Status SessionStatusT
}
Users struct {
store map[string]*User
stLock *sync.RWMutex
}
User struct {
Username string
... | Why multiple password for one user? | )
var (
UserStore *Users = NewUsersStore()
)
type (
SessionStatusT uint8
Session struct {
ID uint64
User *User
CreatedAt time.Time
LastAccessedAt time.Time
Status SessionStatusT
}
Users struct {
store map[string]*User
stLock *sync.RWMutex
}
User struct {
Username str... | @@ -0,0 +1,154 @@
+package core
+
+import (
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/dicedb/dice/config"
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ DefaultUserName = "default"
+ AuthCmd = "AUTH"
+
+ SessionStatusPending SessionStatusT = SessionStatusT(0)
+ SessionStatusActive SessionStatusT = Sess... | core/session.go | 26 | Go | 0.143 | question | 35 | 51 | 51 | false | Add support for Basic Auth | 179 | DiceDB/dice | 10,326 | C | arpitbbhayani | gsarmaonline |
Users struct {
store map[string]*User
stLock *sync.RWMutex
}
User struct {
Username string
Passwords []string
IsPasswordEnabled bool
}
)
func NewUsers() (users *Users) {
users = &Users{
store: make(map[string]*User),
stLock: &sync.RWMutex{},
}
return
}
func (users *Users) Get(... | Reformat this error to how Redis raises it. | Users struct {
store map[string]*User
stLock *sync.RWMutex
}
User struct {
Username string
Passwords []string
IsPasswordEnabled bool
}
)
func NewUsersStore() (users *Users) {
users = &Users{
store: make(map[string]*User),
stLock: &sync.RWMutex{},
}
return
}
func (users *Users)... | @@ -0,0 +1,154 @@
+package core
+
+import (
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/dicedb/dice/config"
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ DefaultUserName = "default"
+ AuthCmd = "AUTH"
+
+ SessionStatusPending SessionStatusT = SessionStatusT(0)
+ SessionStatusActive SessionStatusT = Sess... | core/session.go | 26 | Go | 0.214 | style | 43 | 51 | 51 | false | Add support for Basic Auth | 179 | DiceDB/dice | 10,326 | C | arpitbbhayani | gsarmaonline |
// If any message is added with the ping command,
// the message will be returned.
func evalPING(args []string) []byte {
var b []byte
if len(args) >= 2 {
return Encode(errors.New("ERR wrong number of arguments for 'ping' command"), false)
}
if len(args) == 0 {
b = Encode("PONG", true)
} else {
b = Encode(a... | Do not add log statements. We are yet to define logging standards. | // If any message is added with the ping command,
// the message will be returned.
func evalPING(args []string) []byte {
var b []byte
if len(args) >= 2 {
return Encode(errors.New("ERR wrong number of arguments for 'ping' command"), false)
}
if len(args) == 0 {
b = Encode("PONG", true)
} else {
b = Encode(a... | @@ -53,6 +54,38 @@ func evalPING(args []string) []byte {
return b
}
+// evalAUTH returns with an encoded "OK" if the user is authenticated
+// If the user is not authenticated, it returns with an encoded error message
+func evalAUTH(args []string, c *Client) []byte {
+ var (
+ b []byte
+ err error
+ )
+ log.Pr... | core/eval.go | 26 | Go | 0.214 | suggestion | 66 | 51 | 51 | false | Add support for Basic Auth | 179 | DiceDB/dice | 10,326 | C | arpitbbhayani | gsarmaonline |
}
c.TxnDiscard()
return RESP_OK
}
if diceCmd.Name == "ABORT" {
return RESP_OK
}
return diceCmd.Eval(cmd.Args)
}
func executeCommandToBuffer(cmd *RedisCmd, buf *bytes.Buffer, c *Client) {
buf.Write(executeCommand(cmd, c))
}
func EvalAndRespond(cmds RedisCmds, c *Client) {
var response []byte
buf := byt... | panic is not a good idea. Panic will terminate the server, which is bad. | c.TxnDiscard()
return RESP_OK
}
if diceCmd.Name == "ABORT" {
return RESP_OK
}
return diceCmd.Eval(cmd.Args)
}
func executeCommandToBuffer(cmd *RedisCmd, buf *bytes.Buffer, c *Client) {
buf.Write(executeCommand(cmd, c))
}
func EvalAndRespond(cmds RedisCmds, c *Client) {
var response []byte
buf := bytes.N... | @@ -1013,6 +1049,15 @@ func EvalAndRespond(cmds RedisCmds, c *Client) {
buf := bytes.NewBuffer(response)
for _, cmd := range cmds {
+ // Check if the command has been authenticated
+ if cmd.Cmd != AuthCmd && !c.Session.IsActive() {
+ // TODO: Check required response
+ log.Println("Session not active for CMD... | core/eval.go | 26 | Go | 0.214 | suggestion | 72 | 51 | 51 | false | Add support for Basic Auth | 179 | DiceDB/dice | 10,326 | C | arpitbbhayani | gsarmaonline |
if hasExpired(obj) {
return RESP_NIL
}
// return the RESP encoded value
return Encode(obj.Value, false)
}
// evalJSONGET retrieves a JSON value stored at the specified key
// args must contain at least the key; (path unused in this implementation)
// Returns RESP_NIL if key is expired or it does not exist
// R... | We don't need to check for key expiry here using `hasExpired()` since `Get()` already internally checks for expiration and returns nil. | }
// return the RESP encoded value
return Encode(obj.Value, false)
}
// evalJSONGET retrieves a JSON value stored at the specified key
// args must contain at least the key; (path unused in this implementation)
// Returns RESP_NIL if key is expired or it does not exist
// Returns encoded error response if incorre... | @@ -121,6 +122,72 @@ func evalGET(args []string) []byte {
return Encode(obj.Value, false)
}
+// evalJSONGET retrieves a JSON value stored at the specified key
+// args must contain at least the key; (path unused in this implementation)
+// Returns RESP_NIL if key is expired or it does not exist
+// Returns encode... | core/eval.go | 26 | Go | 0.5 | suggestion | 135 | 51 | 51 | false | Add support for JSON | 181 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
package core
type Obj struct {
TypeEncoding uint8
// Redis allots 24 bits to these bits, but we will use 32 bits because
// golang does not support bitfields and we need not make this super-complicated
// by merging TypeEncoding + LastAccessedAt in one 32 bit integer.
// But nonetheless, we can benchmark and see ... | This overlaps with `OBJ_TYPE_BITSET` since both of them evaluate to `00100000`.
Maybe for clarity sake we can rewrite `OBJ_TYPE_BITSET` as 2 << 4, and then update `OBJ_TYPE_JSON` to 3 << 4.
nit: also move the new type below the existing types. | package core
type Obj struct {
TypeEncoding uint8
// Redis allots 24 bits to these bits, but we will use 32 bits because
// golang does not support bitfields and we need not make this super-complicated
// by merging TypeEncoding + LastAccessedAt in one 32 bit integer.
// But nonetheless, we can benchmark and see ... | @@ -21,6 +21,9 @@ var OBJ_TYPE_BYTELIST uint8 = 1 << 4
var OBJ_ENCODING_QINT uint8 = 0
var OBJ_ENCODING_QREF uint8 = 1
+var OBJ_TYPE_JSON uint8 = 2 << 4 // 00100000 | core/object.go | 24 | Go | 0.786 | nitpick | 249 | 36 | 36 | false | Add support for JSON | 181 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
if err != nil {
return Encode(errors.New("ERR could not serialize JSON value"), false)
}
// Return the JSON value as an encoded string
return Encode(string(jsonBytes), false)
}
// evalJSONSET stores a JSON value at the specified key
// args must contain at least the key, path (unused in this implementation), an... | use fastjson for unmarshalling | // args must contain at least the key, path (unused in this implementation), and JSON string
// Returns encoded error response if incorrect number of arguments
// Returns encoded error if the JSON string is invalid
// Returns RESP_OK if the JSON value is successfully stored
func evalJSONSET(args []string) []byte {
if ... | @@ -121,6 +122,72 @@ func evalGET(args []string) []byte {
return Encode(obj.Value, false)
}
+// evalJSONGET retrieves a JSON value stored at the specified key
+// args must contain at least the key; (path unused in this implementation)
+// Returns RESP_NIL if key is expired or it does not exist
+// Returns encode... | core/eval.go | 26 | Go | 0.143 | suggestion | 30 | 51 | 51 | false | Add support for JSON | 181 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
package tests
import (
"testing"
"github.com/kinbiko/jsonassert"
"gotest.tools/v3/assert"
)
func TestJSONOperations(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
ja := jsonassert.New(t)
t.Run("Set and Get Integer", func(t *testing.T) {
setCmd := `JSON.SET tools $ 2`
result := fireComman... | use the assertion library used in other tests, no need to add a new one. | package tests
import (
"testing"
"gotest.tools/v3/assert"
)
func TestJSONOperations(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
simpleJSON := `{"name":"John","age":30}`
nestedJSON := `{"name":"Alice","address":{"city":"New York","zip":"10001"},"array":[1,2,3,4,5]}`
specialCharsJSON := `{"... | @@ -0,0 +1,152 @@
+package tests
+
+import (
+ "testing"
+
+ "github.com/kinbiko/jsonassert"
+ "gotest.tools/v3/assert"
+)
+
+func TestJSONOperations(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+ ja := jsonassert.New(t) | tests/json_test.go | 13 | Go | 0.286 | suggestion | 72 | 38 | 38 | false | Add support for JSON | 181 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
ja.Assertf(result.(string), `true`)
})
t.Run("Set and Get Boolean False", func(t *testing.T) {
setCmd := `JSON.SET booleanFalse $ false`
result := fireCommand(conn, setCmd)
assert.Equal(t, "OK", result)
getCmd := `JSON.GET booleanFalse`
result = fireCommand(conn, getCmd)
ja.Assertf(result.(string), `f... | It's better to store the JSON string representation being set and later used for assertion in a single variable and then use the variable in both places.
This improves maintainability and readability. | name: "Set and Get Boolean True",
setCmd: `JSON.SET booleanTrue $ true`,
getCmd: `JSON.GET booleanTrue`,
expected: "true",
},
{
name: "Set and Get Boolean False",
setCmd: `JSON.SET booleanFalse $ false`,
getCmd: `JSON.GET booleanFalse`,
expected: "false",
},
{
name: ... | @@ -0,0 +1,152 @@
+package tests
+
+import (
+ "testing"
+
+ "github.com/kinbiko/jsonassert"
+ "gotest.tools/v3/assert"
+)
+
+func TestJSONOperations(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+ ja := jsonassert.New(t)
+
+ t.Run("Set and Get Integer", func(t *testing.T) {
+ setCmd := `JSON.SET... | tests/json_test.go | 26 | Go | 0.5 | suggestion | 201 | 51 | 51 | false | Add support for JSON | 181 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
func DelByPtr(ptr unsafe.Pointer) bool {
storeMutex.Lock()
defer storeMutex.Unlock()
keypoolMutex.Lock()
defer keypoolMutex.Unlock()
if obj, ok := store[ptr]; ok {
delete(store, ptr)
delete(expires, obj)
delete(keypool, *((*string)(ptr)))
KeyspaceStat[0]["keys"]--
return true
}
return false
}
// List... | I'm unsure if ignoring the error message here is a good idea. We should return the error to the caller if something bad happens | }
func DelByPtr(ptr unsafe.Pointer) bool {
storeMutex.Lock()
defer storeMutex.Unlock()
keypoolMutex.Lock()
defer keypoolMutex.Unlock()
if obj, ok := store[ptr]; ok {
delete(store, ptr)
delete(expires, obj)
delete(keypool, *((*string)(ptr)))
KeyspaceStat[0]["keys"]--
return true
}
return false
}
// L... | @@ -140,6 +145,23 @@ func DelByPtr(ptr unsafe.Pointer) bool {
return false
}
+// List all keys in the store by given pattern
+func Keys(p string) []string {
+ storeMutex.RLock()
+ defer storeMutex.RUnlock()
+ keypoolMutex.RLock()
+ defer keypoolMutex.RUnlock()
+
+ keys := make([]string, 0)
+ for k := range keypool... | core/store.go | 26 | Go | 0.571 | suggestion | 127 | 51 | 51 | false | feat: support KEYS command | 197 | DiceDB/dice | 10,326 | C | JyotinderSingh | mingo023 |
}
func DelByPtr(ptr unsafe.Pointer) bool {
storeMutex.Lock()
defer storeMutex.Unlock()
keypoolMutex.Lock()
defer keypoolMutex.Unlock()
if obj, ok := store[ptr]; ok {
delete(store, ptr)
delete(expires, obj)
delete(keypool, *((*string)(ptr)))
KeyspaceStat[0]["keys"]--
return true
}
return false
}
// L... | We might be able to do a small optimization here, if the pattern is an empty string, then preallocate the slice's capacity to be the same as the length of the keypool (to avoid frequent allocations) | }
return false
}
func DelByPtr(ptr unsafe.Pointer) bool {
storeMutex.Lock()
defer storeMutex.Unlock()
keypoolMutex.Lock()
defer keypoolMutex.Unlock()
if obj, ok := store[ptr]; ok {
delete(store, ptr)
delete(expires, obj)
delete(keypool, *((*string)(ptr)))
KeyspaceStat[0]["keys"]--
return true
}
ret... | @@ -140,6 +145,23 @@ func DelByPtr(ptr unsafe.Pointer) bool {
return false
}
+// List all keys in the store by given pattern
+func Keys(p string) []string {
+ storeMutex.RLock()
+ defer storeMutex.RUnlock()
+ keypoolMutex.RLock()
+ defer keypoolMutex.RUnlock()
+
+ keys := make([]string, 0) | core/store.go | 26 | Go | 0.429 | performance | 198 | 51 | 51 | false | feat: support KEYS command | 197 | DiceDB/dice | 10,326 | C | JyotinderSingh | mingo023 |
package tests
import (
"testing"
"gotest.tools/v3/assert"
)
func TestKeys(t *testing.T) {
conn := getLocalConnection()
for _, tcase := range []DTestCase{
{
InCmds: []string{"SET k v", "KEYS k"},
Out: []interface{}{"OK", []interface{}{"k"}},
},
{
InCmds: []string{"SET good v", "SET great v", "KE... | Please add a test covering the following pattern:
```
h[a-b]llo matches hallo and hbllo
``` | actualSlice, ok := actual.([]interface{})
if !ok {
return false
}
if len(expectedSlice) != len(actualSlice) {
return false
}
for _, e := range expectedSlice {
found := false
for _, a := range actualSlice {
if e == a {
found = true
break
}
}
if !found {
return false
}
}
return t... | @@ -0,0 +1,35 @@
+package tests
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestKeys(t *testing.T) { | tests/keys_test.go | 26 | Go | 0.571 | suggestion | 94 | 36 | 51 | false | feat: support KEYS command | 197 | DiceDB/dice | 10,326 | C | JyotinderSingh | mingo023 |
for {
// 1. Check if the accumulated buffer (rp.buf) contains \r\n before reading
// more data. This ensures the function does not hang if \r\n is split
// across multiple reads.
// 2. Check presence of \r\n in the accumulated buffer (rp.buf.Bytes())
// rather than the temporary buffer (rp.tbuf). This ensure... | Should we also handle the following error cases to make the connection handling robust?
For example:
Connection reset.
Connection closed locally.
Read Timeout.
Here are my thoughts, let me know what do you think:
list of scenarios to handle:
1. EOF (peer closed connection): Detected by comparing the error to... | for {
// 1. Check if the accumulated buffer (rp.buf) contains \r\n before reading
// more data. This ensures the function does not hang if \r\n is split
// across multiple reads.
// 2. Check presence of \r\n in the accumulated buffer (rp.buf.Bytes())
// rather than the temporary buffer (rp.tbuf). This ensure... | @@ -61,6 +61,12 @@ func (rp *RESPParser) DecodeOne() (interface{}, error) {
}
return nil, err
}
+
+ // Handle the case where no data is read but no error is returned | core/io.go | 26 | Go | 0.643 | question | 737 | 51 | 51 | false | #196: Fixed DiceDB server reconnection error. | 208 | DiceDB/dice | 10,326 | C | soumya-codes | cam4phor |
// across multiple reads.
// 2. Check presence of \r\n in the accumulated buffer (rp.buf.Bytes())
// rather than the temporary buffer (rp.tbuf). This ensures that data read
// across multiple iterations of the loop is correctly considered.
if rp.buf.Len() > 0 && bytes.Contains(rp.buf.Bytes(), []byte{'\r', '\n... | IMO, it may be good to return a standard error for example net.ErrClosed and have the capability to have different handling for different error scenarios in the calling function. wdyt? | // across multiple reads.
// 2. Check presence of \r\n in the accumulated buffer (rp.buf.Bytes())
// rather than the temporary buffer (rp.tbuf). This ensures that data read
// across multiple iterations of the loop is correctly considered.
if rp.buf.Len() > 0 && bytes.Contains(rp.buf.Bytes(), []byte{'\r', '\n... | @@ -61,6 +61,12 @@ func (rp *RESPParser) DecodeOne() (interface{}, error) {
}
return nil, err
}
+
+ // Handle the case where no data is read but no error is returned
+ if n == 0 {
+ // This can happen if the connection is closed on the client side but not properly detected
+ return nil, errors.New("ERR... | core/io.go | 26 | Go | 0.5 | question | 184 | 51 | 51 | false | #196: Fixed DiceDB server reconnection error. | 208 | DiceDB/dice | 10,326 | C | soumya-codes | cam4phor |
setup: func() {
evalSET([]string{"existent_no_expiry", "value"})
},
output: RESP_MINUS_1,
},
"key exists and expiration removed": {
input: []string{"existent_with_expiry"},
setup: func() {
evalSET([]string{"existent_with_expiry", "value", "EX", "1"})
},
output: RESP_ONE,
},
"key exi... | Let's not use generic names for functions since they can pollute the package namespace. Maybe rename this to `runEvaltests`? | "key exists but no expiration set": {
input: []string{"existent_no_expiry"},
setup: func() {
evalSET([]string{"existent_no_expiry", "value"})
},
output: RESP_MINUS_1,
},
"key exists and expiration removed": {
input: []string{"existent_with_expiry"},
setup: func() {
evalSET([]string{"exis... | @@ -61,82 +118,337 @@ func testEvalMSET(t *testing.T) {
runTests(t, tests, evalMSET)
}
-func runTests(t *testing.T, tests map[string]testCase, evalFunc func([]string) []byte) {
- for name, tc := range tests {
- t.Run(name, func(t *testing.T) {
- output := evalFunc(tc.input)
- assert.Equal(t, string(tc.output)... | core/eval_test.go | 26 | Go | 0.571 | question | 124 | 51 | 51 | false | #198: Adding unit tests for eval.go file | 210 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
"errors"
"strconv"
"strings"
"testing"
"time"
"unsafe"
"github.com/bytedance/sonic"
"gotest.tools/v3/assert"
)
type testCase struct {
setup func()
input []string
output []byte
validator func(output []byte)
}
func setupTest() {
store = make(map[unsafe.Pointer]*Obj)
keypool = make(map[string]u... | This is probably not needed if you are already calling `setupTest()` | "errors"
"strconv"
"strings"
"testing"
"time"
"unsafe"
"github.com/bytedance/sonic"
"gotest.tools/v3/assert"
)
type evalTestCase struct {
setup func()
input []string
output []byte
validator func(output []byte)
}
func resetStore() {
store = nil
keypool = nil
expires = nil
KeyspaceStat[0] = ... | @@ -1,30 +1,87 @@
package core
import (
+ "bytes"
"errors"
"strconv"
+ "strings"
"testing"
"time"
+ "unsafe"
+ "github.com/bytedance/sonic"
"gotest.tools/v3/assert"
)
type testCase struct {
- input []string
- output []byte
+ setup func()
+ input []string
+ output []byte
+ validator func(... | core/eval_test.go | 26 | Go | 0.357 | suggestion | 68 | 51 | 51 | false | #198: Adding unit tests for eval.go file | 210 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
"time"
"unsafe"
"github.com/bytedance/sonic"
"gotest.tools/v3/assert"
)
type testCase struct {
setup func()
input []string
output []byte
validator func(output []byte)
}
func setupTest() {
store = make(map[unsafe.Pointer]*Obj)
keypool = make(map[string]unsafe.Pointer)
expires = make(map[*Obj]uin... | You can call `RestetStore()` here instead.
I also noticed that `ResetStore()` doesn't reset the KeyspaceStat map, so please add the line below into the ResetStore function as well as a part of this PR. | "time"
"unsafe"
"github.com/bytedance/sonic"
"gotest.tools/v3/assert"
)
type evalTestCase struct {
setup func()
input []string
output []byte
validator func(output []byte)
}
func resetStore() {
store = nil
keypool = nil
expires = nil
KeyspaceStat[0] = nil
}
func setupTest() {
resetStore()
st... | @@ -1,30 +1,87 @@
package core
import (
+ "bytes"
"errors"
"strconv"
+ "strings"
"testing"
"time"
+ "unsafe"
+ "github.com/bytedance/sonic"
"gotest.tools/v3/assert"
)
type testCase struct {
- input []string
- output []byte
+ setup func()
+ input []string
+ output []byte
+ validator func(... | core/eval_test.go | 26 | Go | 0.643 | suggestion | 202 | 51 | 51 | false | #198: Adding unit tests for eval.go file | 210 | DiceDB/dice | 10,326 | C | JyotinderSingh | lucifercr07 |
case "EX", "ex":
i++
if i == len(args) {
return Encode(errors.New("ERR syntax error"), false)
}
exDurationSec, err := strconv.ParseInt(args[i], 10, 64)
if err != nil {
return Encode(errors.New("ERR value is not an integer or out of range"), false)
}
exDurationMs = exDurationSec * 1000
... | This behaviour doesn't reflect the same what's done in redis.
Redis does not reject the `EXAT` value if it is in the past. Instead, it sets the key and immediately expires it if the timestamp has already passed.
@JyotinderSingh @arpitbbhayani please correct me if I'm wrong here. |
for i := 2; i < len(args); i++ {
switch args[i] {
case "EX", "ex":
i++
if i == len(args) {
return Encode(errors.New("ERR syntax error"), false)
}
exDurationSec, err := strconv.ParseInt(args[i], 10, 64)
if err != nil {
return Encode(errors.New("ERR value is not an integer or out of range"),... | @@ -87,6 +88,25 @@ func evalSET(args []string) []byte {
return Encode(errors.New("ERR value is not an integer or out of range"), false)
}
exDurationMs = exDurationSec * 1000
+
+ case "EXAT", "exat":
+ i++
+ if i == len(args) {
+ return Encode(errors.New("ERR syntax error"), false)
+ }
+
+ exAt,... | core/eval.go | 26 | Go | 0.643 | bug | 282 | 51 | 51 | false | Add support for EXAT in SET command | 218 | DiceDB/dice | 10,326 | C | lucifercr07 | colommar |
var exDurationMs int64 = -1
key, value = args[0], args[1]
oType, oEnc := deduceTypeEncoding(value)
for i := 2; i < len(args); i++ {
switch args[i] {
case "EX", "ex":
i++
if i == len(args) {
return Encode(errors.New("ERR syntax error"), false)
}
exDurationSec, err := strconv.ParseInt(args[i], ... | We also need to add positive integer check. | }
var key, value string
var exDurationMs int64 = -1
key, value = args[0], args[1]
oType, oEnc := deduceTypeEncoding(value)
for i := 2; i < len(args); i++ {
switch args[i] {
case "EX", "ex":
i++
if i == len(args) {
return Encode(errors.New("ERR syntax error"), false)
}
exDurationSec, err :=... | @@ -87,6 +88,25 @@ func evalSET(args []string) []byte {
return Encode(errors.New("ERR value is not an integer or out of range"), false)
}
exDurationMs = exDurationSec * 1000
+
+ case "EXAT", "exat":
+ i++
+ if i == len(args) {
+ return Encode(errors.New("ERR syntax error"), false)
+ }
+
+ exAt,... | core/eval.go | 26 | Go | 0.071 | suggestion | 43 | 51 | 51 | false | Add support for EXAT in SET command | 218 | DiceDB/dice | 10,326 | C | lucifercr07 | colommar |
if i == len(args) {
return Encode(errors.New("ERR syntax error"), false)
}
exAt, err := strconv.ParseInt(args[i], 10, 64)
if err != nil {
return Encode(errors.New("ERR value is not an integer or out of range"), false)
}
currentTime := time.Now().Unix()
if exAt <= currentTime {
return ... | Nit: Please remove if unintentional |
case "PXAT", "pxat":
i++
if i == len(args) {
return Encode(errors.New("ERR syntax error"), false)
}
exDurationUnixMs, err := strconv.ParseInt(args[i], 10, 64)
if err != nil {
return Encode(errors.New("ERR value is not an integer or out of range"), false)
}
if exDurationUnixMs < 0 {
... | @@ -96,6 +116,7 @@ func evalSET(args []string) []byte {
return RESP_NIL
}
+ | core/eval.go | 26 | Go | 0.143 | nitpick | 35 | 51 | 51 | false | Add support for EXAT in SET command | 218 | DiceDB/dice | 10,326 | C | lucifercr07 | colommar |
package tests
import (
"fmt"
"net"
"testing"
"gotest.tools/v3/assert"
)
func deleteKeys(conn net.Conn, keysToDelete []string) {
for _, key := range keysToDelete {
fireCommand(conn, fmt.Sprintf("DEL %s", key))
}
}
func TestSet(t *testing.T) {
conn := getLocalConnection()
for _, tcase := range []DTestCase{
... | Let's rename this to `deleteTestKeys` and move it to tests/setup.go. | package tests
import (
"testing"
"gotest.tools/v3/assert"
)
func TestSet(t *testing.T) {
conn := getLocalConnection()
for _, tcase := range []DTestCase{
{
InCmds: []string{"SET k v", "GET k"},
Out: []interface{}{"OK", "v"},
},
} {
for i := 0; i < len(tcase.InCmds); i++ {
cmd := tcase.InCmds[i]... | @@ -1,11 +1,19 @@
package tests
import (
+ "fmt"
+ "net"
"testing"
"gotest.tools/v3/assert"
)
+func deleteKeys(conn net.Conn, keysToDelete []string) { | tests/set_test.go | 11 | Go | 0.429 | suggestion | 68 | 36 | 36 | false | #205: Add support for XX in SET command | 220 | DiceDB/dice | 10,326 | C | JyotinderSingh | sanuj96 |
import (
"testing"
"gotest.tools/v3/assert"
)
func TestSet(t *testing.T) {
conn := getLocalConnection()
for _, tcase := range []DTestCase{
{
InCmds: []string{"SET k v", "GET k"},
Out: []interface{}{"OK", "v"},
},
} {
for i := 0; i < len(tcase.InCmds); i++ {
cmd := tcase.InCmds[i]
out := tcas... | Whetever keys you are planning to use in your test make sure to clean them up by calling deleteTestKeys utility | import (
"gotest.tools/v3/assert"
"strconv"
"testing"
"time"
)
func TestSet(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
testCases := []struct {
name string
commands []string
expected []interface{}
}{
{
name: "Set and Get Simple Value",
commands: []string{"SET k v", "G... | @@ -21,3 +21,37 @@ func TestSet(t *testing.T) {
}
}
}
+func TestSetWithNX(t *testing.T) {
+ conn := getLocalConnection()
+ for _, tcase := range []DTestCase{
+ {
+ InCmds: []string{"SET K V NX", "GET K"}, | tests/set_test.go | 26 | Go | 0.429 | refactor | 111 | 51 | 51 | false | Added support NX for SET command | 227 | DiceDB/dice | 10,326 | C | sanuj96 | chanducheryala |
setCmd: `JSON.SET escaped $ ` + escapedCharsJSON,
getCmd: `JSON.GET escaped`,
expected: escapedCharsJSON,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if tc.setCmd != "" {
result := fireCommand(conn, tc.setCmd)
if tc.name != "Set Invalid JSON" && tc.name != "Set... | IMO you should add these tests to set_test.go file instead. @JyotinderSingh wdyt? | },
{
name: "Set JSON with Escaped Characters",
setCmd: `JSON.SET escaped $ ` + escapedCharsJSON,
getCmd: `JSON.GET escaped`,
expected: escapedCharsJSON,
},
{
name: "Set and Get Complex JSON",
setCmd: `JSON.SET inventory $ ` + complexJSON,
getCmd: `JSON.GET inventory`,
exp... | @@ -131,3 +131,37 @@ func TestJSONOperations(t *testing.T) {
})
}
}
+
+func TestJSONSetWithNXAndXX(t *testing.T) { | tests/json_test.go | 26 | Go | 0.286 | question | 81 | 51 | 51 | false | Added support for NX | XX in JSON.SET command | 228 | DiceDB/dice | 10,326 | C | soumya-codes | vaibh1297 |
obj := Get(key)
// if key does not exist, return RESP encoded -2 denoting key does not exist
if obj == nil {
return RESP_MINUS_2
}
// if object exist, but no expiration is set on it then send -1
exp, isExpirySet := getExpiry(obj)
if !isExpirySet {
return RESP_MINUS_1
}
// compute the time remaining for ... | We should also handle the case:
`JSON.SET user $ '{"name":"John","age":30}' NX XX`
Below is the output from REDIS:
```
redis:6379> JSON.SET user $ '{"name":"John","age":30}' NX XX
(error) ERR unknown command 'JSON.SET', with args beginning with: 'user' '$' '{"name":"John","age":30}' 'NX' 'XX'
``` | resultBytes, err = json.Marshal(results)
}
if err != nil {
return Encode(errors.New("ERR could not serialize result"), false)
}
return Encode(string(resultBytes), false)
}
// evalJSONSET stores a JSON value at the specified key
// args must contain at least the key, path (unused in this implementation), and JS... | @@ -173,6 +173,24 @@ func evalJSONSET(args []string) []byte {
// Note: args[1] (path) is ignored in this implementation
jsonStr := args[2]
+ for i := 3; i < len(args); i++ {
+ switch args[i] {
+ case "NX", "nx": | core/eval.go | 26 | Go | 1 | suggestion | 305 | 51 | 51 | false | Added support for NX | XX in JSON.SET command | 228 | DiceDB/dice | 10,326 | C | soumya-codes | vaibh1297 |
// Test for removing from queue with multiple non-expired keys
func TestRemoveMultipleNonExpiredKeys(t *testing.T) {
qr := core.NewQueueRef()
val := [3]int{10, 20, 30}
core.Put("key1", core.NewObj(val[0], -1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key1")
core.Put("key2", core.NewObj(val[1], -1, c... | The expiration time is in seconds, therefore the sleep interval should also be in seconds. Same for other occurrences in this file. |
// Test for removing from queue with multiple non-expired keys
func TestRemoveMultipleNonExpiredKeys(t *testing.T) {
qr := core.NewQueueRef()
val := [3]int{10, 20, 30}
core.Put("key1", core.NewObj(val[0], -1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key1")
core.Put("key2", core.NewObj(val[1], -1, ... | @@ -56,3 +59,152 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 0.429 | suggestion | 131 | 51 | 51 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
// Test for removing from queue with single non-expired keys
func TestRemoveSingleNonExpiredKeys(t *testing.T) {
qr := core.NewQueueRef()
val := 10
core.Put("key1", core.NewObj(val, -1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key1")
if qe, err := qr.Remove(); err != nil || qe.Obj.Value != val {
... | Please use the assert library for consistency. | }
// Test for removing from queue with single non-expired keys
func TestRemoveSingleNonExpiredKeys(t *testing.T) {
qr := core.NewQueueRef()
val := 10
core.Put("key1", core.NewObj(val, -1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key1")
qe, err := qr.Remove()
assert.Check(t, err == nil || qe.Obj.V... | @@ -56,3 +59,152 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 0.143 | style | 46 | 51 | 51 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
core.Put("key2", core.NewObj(val[1], 1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key2")
core.Put("key3", core.NewObj(val[2], -1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key3")
time.Sleep(2 * time.Millisecond)
if qe, err := qr.Remove(); err != nil || qe.Obj.Value != val[2] {
t.Er... | I have a few suggestions to improve the benchmark:
1. Let's split the benchmark into separate operations - insertion and removal. This will give us more granular performance insights for each operation.
2. Please use `b.Run()` calls to create sub-benchmarks for different data sizes and operations.
3. Call `b.Reset... | core.Put("key3", core.NewObj(val[2], -1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key3")
time.Sleep(2 * time.Millisecond)
fmt.Printf("Queue size : %d\n", qr.Length())
qe, err := qr.Remove()
assert.Check(t, err == nil || qe.Obj.Value == val[2], fmt.Sprintf("test for removing mulitple expired key be... | @@ -56,3 +59,152 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 1 | performance | 1,421 | 51 | 51 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
// Test for removing from queue with all expired keys
func TestRemoveAllExpired(t *testing.T) {
qr := core.NewQueueRef()
val := [3]int{10, 20, 30}
core.Put("key1", core.NewObj(val[0], 1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key1")
core.Put("key2", core.NewObj(val[1], 1, core.OBJ_TYPE_STRING, c... | Trying to understand something. Should the `expiredLast` not be equal to `nonExpired`?
You are waiting for 2ms before you run the benchmark for qr.Remove(), wouldn't the `expiredFirst` keys have expired by then?
If my understanding is correct then it may be better to call the Remove() operation only `nonExpired` nu... | }
// Test for removing from queue with all expired keys
func TestRemoveAllExpired(t *testing.T) {
qr := core.NewQueueRef()
val := [3]int{10, 20, 30}
core.Put("key1", core.NewObj(val[0], 1, core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert("key1")
core.Put("key2", core.NewObj(val[1], 1, core.OBJ_TYPE_STRING,... | @@ -56,3 +61,130 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 0.643 | suggestion | 533 | 51 | 51 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
// need to init again for each round with the overriden buffer size
// otherwise the watchchannel buffer size will stay as it is with the global keylimits size
core.WatchChannel = make(chan core.WatchEvent, config.KeysLimit)
b.ResetTimer()
for _, bc := range benchmarkCases {
b.Run(fmt.Sprintf("%s Insert expire... | These two insertions can be done as a part of the same `b.Run()` function. | value := fmt.Sprintf("v%d", i)
random := rand.Intn(2)
// Insert keys without expiration
expiration := -1
if random == 1 {
// Insert keys with expiration of 1ms
expiration = 1
expiredCount++
} else {
nonExpiredCount++
}
core.Put(key, core.NewObj(value, int64(expiration), core.OBJ_... | @@ -56,3 +61,130 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 0.357 | suggestion | 74 | 40 | 37 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
} else {
nonExpiredCount++
}
core.Put(key, core.NewObj(value, int64(expiration), core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert(key)
}
})
len := qr.Length()
fmt.Printf("Queue length before removal : %d\n", len)
fmt.Printf("Inserted keys count, expired : %d , non-expired : %d\n", expiredCo... | No need for print statements, they add unnecessary noise to console output. This can be removed | } else {
nonExpiredCount++
}
core.Put(key, core.NewObj(value, int64(expiration), core.OBJ_TYPE_STRING, core.OBJ_ENCODING_INT))
qr.Insert(key)
}
})
b.StopTimer()
// Allow keys to expire
time.Sleep(2 * time.Millisecond)
b.StartTimer()
b.Run("Removal of keys", func(b *testing.B) {
for i := 0; i ... | @@ -56,3 +61,129 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 0.286 | suggestion | 95 | 31 | 29 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
core.WatchChannel = make(chan core.WatchEvent, config.KeysLimit)
b.ResetTimer()
expiredCount := 0
nonExpiredCount := 0
b.Run("Insertion of expired and non-expired keys", func(b *testing.B) {
for i := 0; i < b.N; i++ {
key := fmt.Sprintf("k%d", i)
value := fmt.Sprintf("v%d", i)
random := rand.Intn(2)
... | Stop and start timer around the sleep duration. | core.WatchChannel = make(chan core.WatchEvent, config.KeysLimit)
expiredCount := 0
nonExpiredCount := 0
b.ResetTimer()
b.Run("Insertion of expired and non-expired keys", func(b *testing.B) {
for i := 0; i < b.N; i++ {
key := fmt.Sprintf("k%d", i)
value := fmt.Sprintf("v%d", i)
random := rand.Intn(2)
... | @@ -56,3 +61,129 @@ func TestQueueRef(t *testing.T) {
t.Error("iterating through the queueref should return the objs in the order they were added. Expected: ", expectedVals, " Got: ", observedVals)
}
}
+
+// Test for removing from queue with single non-expired keys
+func TestRemoveSingleNonExpiredKeys(t *testing.... | core/queueref_test.go | 26 | Go | 0.071 | suggestion | 47 | 47 | 45 | false | #184 : Test cases and benchmarking for queueref remove | 229 | DiceDB/dice | 10,326 | C | JyotinderSingh | VipinRaiP |
// return the RESP encoded value
return Encode(obj.Value, false)
}
// evalJSONGET retrieves a JSON value stored at the specified key
// args must contain at least the key; (path unused in this implementation)
// Returns RESP_NIL if key is expired or it does not exist
// Returns encoded error response if incorrect ... | no need to check `hasExpired`, since this check already happens inside the `Get` call. | return Encode(errors.New("ERR syntax error"), false)
}
}
// putting the k and value in a Hash Table
Put(key, NewObj(value, exDurationMs, oType, oEnc))
return RESP_OK
}
// evalGET returns the value for the queried key in args
// The key should be the only param in args
// The RESP value of the key is encoded ... | @@ -135,53 +135,121 @@ func evalGET(args []string) []byte {
// Returns encoded error response if incorrect number of arguments
// The RESP value of the key is encoded and then returned
func evalJSONGET(args []string) []byte {
+ // Check if there are enough arguments
if len(args) < 1 {
return Encode(errors.New("... | core/eval.go | 26 | Go | 0.357 | suggestion | 86 | 51 | 51 | false | #166: Adds JSONPath Support | 235 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
// evalJSONGET retrieves a JSON value stored at the specified key
// args must contain at least the key; (path unused in this implementation)
// Returns RESP_NIL if key is expired or it does not exist
// Returns encoded error response if incorrect number of arguments
// The RESP value of the key is encoded and then re... | Use `assertType` and `assertEncoding` methods for type and encoding verification. | Put(key, NewObj(value, exDurationMs, oType, oEnc))
return RESP_OK
}
// evalGET returns the value for the queried key in args
// The key should be the only param in args
// The RESP value of the key is encoded and then returned
// evalGET returns RESP_NIL if key is expired or it does not exist
func evalGET(args []str... | @@ -135,53 +135,121 @@ func evalGET(args []string) []byte {
// Returns encoded error response if incorrect number of arguments
// The RESP value of the key is encoded and then returned
func evalJSONGET(args []string) []byte {
+ // Check if there are enough arguments
if len(args) < 1 {
return Encode(errors.New("... | core/eval.go | 26 | Go | 0.571 | suggestion | 81 | 51 | 51 | false | #166: Adds JSONPath Support | 235 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
}
key := args[0]
path := args[1]
jsonStr := args[2]
// Parse the JSON string
var jsonValue interface{}
if err := json.Unmarshal([]byte(jsonStr), &jsonValue); err != nil {
return Encode(fmt.Errorf("ERR invalid JSON: %v", err), false)
}
// Retrieve existing object or create new one
obj := Get(key)
var roo... | Use `assertType` and `assertEncoding` methods for type and encoding verification. | return Encode(errors.New("ERR invalid JSONPath"), false)
}
// Execute the JSONPath query
results := expr.Get(jsonData)
if len(results) == 0 {
return RESP_NIL
}
// Serialize the result
var resultBytes []byte
if len(results) == 1 {
resultBytes, err = json.Marshal(results[0])
} else {
resultBytes, err =... | @@ -135,53 +135,121 @@ func evalGET(args []string) []byte {
// Returns encoded error response if incorrect number of arguments
// The RESP value of the key is encoded and then returned
func evalJSONGET(args []string) []byte {
+ // Check if there are enough arguments
if len(args) < 1 {
return Encode(errors.New("... | core/eval.go | 26 | Go | 0.571 | suggestion | 81 | 51 | 51 | false | #166: Adds JSONPath Support | 235 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
// Get the key from the hash table
obj := Get(key)
// if key does not exist, return RESP encoded nil
if obj == nil {
return RESP_NIL
}
// return the RESP encoded value
return Encode(obj.Value, false)
}
// evalJSONGET retrieves a JSON value stored at the specified key
// args must contain at least the key; ... | Store `$` in a constant and use that constant in both the eval methods. | obj := Get(key)
// if key does not exist, return RESP encoded nil
if obj == nil {
return RESP_NIL
}
default:
return Encode(errors.New("ERR syntax error"), false)
}
}
// putting the k and value in a Hash Table
Put(key, NewObj(value, exDurationMs, oType, oEnc))
return RESP_OK
}
// evalGET re... | @@ -135,53 +135,121 @@ func evalGET(args []string) []byte {
// Returns encoded error response if incorrect number of arguments
// The RESP value of the key is encoded and then returned
func evalJSONGET(args []string) []byte {
+ // Check if there are enough arguments
if len(args) < 1 {
return Encode(errors.New("... | core/eval.go | 26 | Go | 0.429 | suggestion | 71 | 51 | 51 | false | #166: Adds JSONPath Support | 235 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
package tests
import (
"encoding/json"
"reflect"
"testing"
"gotest.tools/v3/assert"
)
func TestJSONOperations(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
simpleJSON := `{"name":"John","age":30}`
nestedJSON := `{"name":"Alice","address":{"city":"New York","zip":"10001"},"array":[1,2,3,4,5... | Let's move these helpers into a new file under `testutils`, `testutils/json.go` | package tests
import (
"testing"
"github.com/dicedb/dice/testutils"
"gotest.tools/v3/assert"
)
func TestJSONOperations(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
simpleJSON := `{"name":"John","age":30}`
nestedJSON := `{"name":"Alice","address":{"city":"New York","zip":"10001"},"array":[1... | @@ -127,8 +166,48 @@ func TestJSONOperations(t *testing.T) {
if tc.getCmd != "" {
result := fireCommand(conn, tc.getCmd)
- assert.DeepEqual(t, tc.expected, result)
+ if isJSONResponse(result.(string)) {
+ assertJSONEqual(t, tc.expected, result.(string))
+ } else {
+ assert.Equal(t, tc.expect... | tests/json_test.go | 26 | Go | 0.429 | refactor | 79 | 214 | 221 | false | #166: Adds JSONPath Support | 235 | DiceDB/dice | 10,326 | C | JyotinderSingh | Maveric-k07 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.