Skip to content

Commit

Permalink
Merge pull request #24 from P4-Games/feature/open-pack-improvements
Browse files Browse the repository at this point in the history
Feature/open pack improvements
  • Loading branch information
dappsar authored Nov 14, 2023
2 parents f9dd9f1 + 86fa497 commit eb73223
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 86 deletions.
61 changes: 38 additions & 23 deletions contracts/gamma/GammaCards.v2.sol
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ contract NofGammaCardsV2 is ERC721, ERC721URIStorage, ERC721Burnable, Ownable {
uint256 public secondaryAlbumPrize = 1e18; // 1 DAI por album secundario completado
string public mainUri;
string public secondaryUri;
bool public requireOpenPackSignerValidation;
mapping (uint256 cardNumber => uint256 amount) public cardsInventory; // maximos: 119 => 4999
mapping (uint256 tokenId => Card) public cards;
mapping(address user => mapping(uint8 cardNumber => uint8 amount)) public cardsByUser;
Expand All @@ -69,6 +70,21 @@ contract NofGammaCardsV2 is ERC721, ERC721URIStorage, ERC721Burnable, Ownable {
event NewSigner(address newSigner);
event NewUris(string newMainUri, string newSecondaryUri);

constructor(address _daiTokenAddress, address _packsContract, string memory _baseUri, address _signer)
ERC721("GammaCards", "NOF_GC") {
packsContract = IGammaPacks(_packsContract);
DAI_TOKEN = _daiTokenAddress;
baseUri = _baseUri;
mainUri = string(abi.encodePacked(bytes(baseUri), bytes("/"), bytes("120"), bytes("F.json")));
secondaryUri = string(abi.encodePacked(bytes(baseUri), bytes("/"), bytes("121"), bytes("F.json")));
signers[_signer] = true;
requireOpenPackSignerValidation = false;
for(uint256 i;i<122;i++){
cardsInventory[i] = 1;
}
owners[msg.sender] = true;
}

modifier onlyPacksContract {
require(msg.sender == address(packsContract), "Solo contrato de packs");
_;
Expand Down Expand Up @@ -105,40 +121,39 @@ contract NofGammaCardsV2 is ERC721, ERC721URIStorage, ERC721Burnable, Ownable {
signers[_signerToRemove] = false;
}

constructor(address _daiTokenAddress, address _packsContract, string memory _baseUri, address _signer)
ERC721("GammaCards", "NOF_GC") {
packsContract = IGammaPacks(_packsContract);
DAI_TOKEN = _daiTokenAddress;
baseUri = _baseUri;
mainUri = string(abi.encodePacked(bytes(baseUri), bytes("/"), bytes("120"), bytes("F.json")));
secondaryUri = string(abi.encodePacked(bytes(baseUri), bytes("/"), bytes("121"), bytes("F.json")));
signers[_signer] = true;
for(uint256 i;i<122;i++){
cardsInventory[i] = 1;
}
owners[msg.sender] = true;
function changeRequireOpenPackSignerValidation(bool required) external onlyOwners {
requireOpenPackSignerValidation = required;
}

function verifyPackSigner(uint256 packNumber, uint8[] memory packData, bytes calldata signature) public view
returns (address signer) {
bytes32 messageHash = keccak256(abi.encodePacked(msg.sender, packNumber,
packData, '0xf1dD71895e49b1563693969de50898197cDF3481')).toEthSignedMessageHash();
address recoveredSigner = messageHash.recover(signature);
console.log('open pack signer recovered', recoveredSigner);
return recoveredSigner;
}

function openPack(uint256 packNumber, uint8[] memory packData, bytes calldata signature) external {
require(packsContract.getPackOwner(packNumber) == msg.sender, "Este sobre no es tuyo");
require(packData.length < 15, "Limite de cartas excedido"); // chequear este length

packsContract.openPack(packNumber, msg.sender);
prizesBalance += packPrice - packPrice / 6;

// Recreates the message present in the `signature`
bytes32 messageHash =
keccak256(abi.encodePacked(
msg.sender, packNumber,
if (requireOpenPackSignerValidation) {
// Recreates the message present in the `signature`
bytes32 messageHash = keccak256(abi.encodePacked(msg.sender, packNumber,
packData, '0xf1dD71895e49b1563693969de50898197cDF3481')).toEthSignedMessageHash();

address recoveredSigner = messageHash.recover(signature);
console.log('open pack signer recovered', recoveredSigner);
require(signers[recoveredSigner], "Invalid signature");
address recoveredSigner = messageHash.recover(signature);
console.log('open pack signer recovered', recoveredSigner);
require(signers[recoveredSigner], "Invalid signature");
}

packsContract.openPack(packNumber, msg.sender);
prizesBalance += packPrice - packPrice / 6;
uint256 length = packData.length;
for(uint8 i;i<length;i++){
require(packData[i] == 120 ? cardsInventory[120] < 3001 : cardsInventory[packData[i]] < 5001);
require(packData[i] == 120 ? cardsInventory[120] < 3001 : cardsInventory[packData[i]] < 5001,
'invalid cardInventory position');
cardsInventory[packData[i]]++; // 280k gas aprox.
cardsByUser[msg.sender][packData[i]]++; // 310k gas aprox.
}
Expand Down
13 changes: 8 additions & 5 deletions scripts/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';
import Web3 from 'web3';
import { config } from 'hardhat';

const isLocalhost = (network.name === 'localhost') || (network.name === '127.0.0.1')
const isHardhat = (network.name === 'hardhat')
export const isLocalhost = (network.name === 'localhost') || (network.name === '127.0.0.1')
export const isHardhat = (network.name === 'hardhat')

export async function getInitData() {
if (isHardhat) {
Expand Down Expand Up @@ -43,7 +43,9 @@ export async function deployContracts(addresses: SignerWithAddress[]) {
const additionalOwners = (process.env.ADDITIONAL_OWNERS_WALLETS_ADDRESSES
|| '0x35dad65F60c1A32c9895BE97f6bcE57D32792E83,0x8a8F5e5ae88532c605921f320a92562c9599fB9E').split(',')
const balanceReceiverAddress =
(isLocalhost || isHardhat) ? addresses[0].address : (process.env.BALANCE_RECEIVER_WALLET_ADDRESS || '0x6b510284C49705eA14e92aD35D86FD3075eC56e0')
(isLocalhost || isHardhat)
? addresses[0].address
: (process.env.BALANCE_RECEIVER_WALLET_ADDRESS || '0x6b510284C49705eA14e92aD35D86FD3075eC56e0')

console.log(`deploying contract ${nofDaiContractName}`)
const TestDAI = await ethers.getContractFactory(nofDaiContractName);
Expand All @@ -52,7 +54,7 @@ export async function deployContracts(addresses: SignerWithAddress[]) {

console.log(`deploying contract ${nofAlphaContractName}`)
const Alpha = await ethers.getContractFactory(nofAlphaContractName);
const alpha = await Alpha.deploy('https://nof.town', testDAI.address, balanceReceiverAddress);
const alpha = await Alpha.deploy('https://storage.googleapis.com/nof-alfa/T1', testDAI.address, balanceReceiverAddress);
await alpha.deployed();

console.log(`deploying contract ${nofGammaPacksContractName}`)
Expand All @@ -62,7 +64,8 @@ export async function deployContracts(addresses: SignerWithAddress[]) {

console.log(`deploying contract ${nofGammaCardsContractName}`)
const GammaCards = await ethers.getContractFactory(nofGammaCardsContractName);
const gammaCards = await GammaCards.deploy(testDAI.address, gammaPacks.address, 'https://storage.googleapis.com/nof-gamma/T1', microServiceSignatureWalletsAddresses[0]);
const gammaCards = await GammaCards.deploy(testDAI.address, gammaPacks.address,
'https://storage.googleapis.com/nof-gamma/T1', microServiceSignatureWalletsAddresses[0]);
await gammaCards.deployed();
await gammaPacks.setCardsContract(gammaCards.address);

Expand Down
110 changes: 53 additions & 57 deletions scripts/deploy-mock-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import "@nomiclabs/hardhat-ethers";
import { ethers } from "hardhat";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import { Contract } from "ethers";
import { generateSignature, getInitData, deployContracts } from "./common";
import { generateSignature, getInitData, deployContracts, isHardhat, isLocalhost } from "./common";

async function createAlphaMockData( addresses: SignerWithAddress[], testDAI: Contract, alpha: Contract ) {
// Alpha Data
Expand Down Expand Up @@ -61,66 +61,62 @@ async function createGammaMockData(
const allowance = await testDAI.allowance(addresses[0].address, gammaPacks.address)
console.log(`${addresses[0].address} allowance to use with $ gamaPackAddress (${gammaPacks.address}): `, allowance)

console.log('buying Pack...')
const estimatedGas = await gammaPacks.estimateGas.buyPack();
console.log('buying Pack, estimated gas', estimatedGas)

const gasLimit = estimatedGas.add(10000) // security-margin
const tokenId = await gammaPacks.buyPack({ gasLimit, from: addresses[0].address });
console.log('Buyed Pack token Id', tokenId.value)

console.log('Verifing testDai balance...')
const balance2 = await testDAI.balanceOf(addresses[0].address)
console.log(`${addresses[0].address} balance: `, balance2)

console.log('Verifing testDai allowance...')
const allowance2 = await testDAI.allowance(addresses[0].address, gammaPacks.address)
console.log(`${addresses[0].address} allowance to use with $ gamaPackAddress (${gammaPacks.address}): `, allowance2)

console.log('Verifing pack owner...')
const packOwner = await gammaPacks.getPackOwner(tokenId.value)
console.log(`Owner of TokenId ${tokenId.value}: ${packOwner}`)

console.log('buying 3 Packs...')
const estimatedGasTenPacks = await gammaPacks.estimateGas.buyPacks(3);
console.log('buying 3 Packs, estimated gas', estimatedGasTenPacks)

const gasLimitTenPacks = estimatedGasTenPacks.add(10000) // security-margin
await gammaPacks.buyPacks(3, { gasLimit: gasLimitTenPacks, from: addresses[0].address });

console.log('Verifing user\'s packs...')
const packs:[any] = await gammaPacks.getPacksByUser(addresses[0].address)
if (isHardhat || isLocalhost) {
console.log('buying Pack (estimating gas)...')
const estimatedGas = await gammaPacks.estimateGas.buyPack({ from: addresses[0].address });
console.log('buying Pack, estimated gas', estimatedGas)

const gasLimit = estimatedGas.add(20000) // security-margin
console.log('buying Pack (real operation)...')
const tokenId = await gammaPacks.connect(addresses[0]).buyPack({ gasLimit });
console.log('Buyed Pack token Id', tokenId.value)

console.log('Verifing testDai balance...')
const balance2 = await testDAI.balanceOf(addresses[0].address)
console.log(`${addresses[0].address} balance: `, balance2)

console.log('Verifing testDai allowance...')
const allowance2 = await testDAI.allowance(addresses[0].address, gammaPacks.address)
console.log(`${addresses[0].address} allowance to use with $ gamaPackAddress (${gammaPacks.address}): `, allowance2)

console.log('Verifing pack owner...')
const packOwner = await gammaPacks.getPackOwner(tokenId.value)
console.log(`Owner of TokenId ${tokenId.value}: ${packOwner}`)

console.log('buying 2 Packs (estimating gas)...')
const estimatedGasTenPacks = await gammaPacks.estimateGas.buyPacks(2);
console.log('buying 2 Packs, estimated gas', estimatedGasTenPacks)

console.log('buying 2 Packs (operation)...')
const gasLimitTenPacks = estimatedGasTenPacks.add(20000) // security-margin
await gammaPacks.connect(addresses[0]).buyPacks(2, { gasLimit: gasLimitTenPacks });

console.log('Verifing user\'s packs...')
const packs:[any] = await gammaPacks.getPacksByUser(addresses[0].address)

console.log('User\'s packs')
for (let i = 0; i < packs.length-1; i++) {
console.log(`\tPack ${i+1} Id: ${packs[i]}`)
}

console.log('User\'s packs')
for (let i = 0; i < packs.length-1; i++) {
console.log(`\tPack ${i+1} Id: ${packs[i]}`)
}
/*
//
TO-FIX: reason: 'invalid arrayify value',
//
console.log('Opening Pack with cardData simulating backend signature...')
const packNumber = ethers.BigNumber.from(packs[0]).toNumber()
const signatureData: any = await generateSignature(signatureMethod, addresses[0].address, packNumber)
const { packet_data, signature } = signatureData
/*
console.log('Opening Pack with cardData simulating backend signature...')
if (signatureMethod === '1') {
// tiene que cambiar la wallet del signer a la misma que hace la
// firma en el método generateSignature1 (la wallet 0 de hardhat).
// Se hace eso para que luego en el SC, al comparar ambas wallets,
// funciones bien (wallet de firma = signer)
gammaCards.setSigner(addresses[0].address)
// en el caso de deploy fuera de local, el SC tiene que tener como signer
// la dirección de la clave privada que usa el micro-servicio:
// 0x20517cf8c140f7f393f92cea6158f57385a75733
await gammaCards.openPack(packNumber, packet_data, signature)
console.log('User\'s packs')
for (let i = 0; i < packs.length-1; i++) {
console.log(`\tPack ${i+1} Id: ${packs[i]}`)
}
*/
}

const signatureData: any = await generateSignature(signatureMethod, addresses[0].address, 0)
const packNumber = ethers.BigNumber.from(packs[0]).toNumber()
const { packet_data, signature } = signatureData
await gammaCards.openPack(packNumber, packet_data, signature)
*/

console.log('User\'s packs')
for (let i = 0; i < packs.length-1; i++) {
console.log(`\tPack ${i+1} Id: ${packs[i]}`)
}
}

async function main() {
Expand Down
2 changes: 1 addition & 1 deletion test/gamma.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe('NoF - Gamma Tests', function () {
expect(packOwner).to.equal(address0.address)
})

it("Pack could be open by its owner", async () => {
it('Pack could be open by its owner', async () => {
const { testDAI, gammaPacks, gammaCards, address0 } = await loadFixture(deployNofFixture)
const TenPacksPrice = ethers.BigNumber.from('10000000000000000000'.toString())
await testDAI._mint(address0.address, TenPacksPrice)
Expand Down

0 comments on commit eb73223

Please sign in to comment.