diff --git a/.env b/.env index 2c0080c6..92c86dc8 100644 --- a/.env +++ b/.env @@ -8,11 +8,11 @@ pair=11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59 CHAIN_NAME=casper-test NODE_ADDRESS=http://159.65.118.250:7777/rpc -EVENT_STREAM_ADDRESS=http://159.65.118.250:7777/events/main +EVENT_STREAM_ADDRESS=http://159.65.118.250:9999/events/main RECEIVER_ACCOUNT_ONE=017e82abcc9539a01cfd9d63ae8c9c8b3a752a6f75ba1ab148714eea03e9be69a7 ERC20_WASM_PATH=JsClients/ERC20/wasm/erc20-token.wasm -FACTORY_WASM_PATH=JsClients/FACTORY/wasm/factory-token.wasm +FACTORY_WASM_PATH=JsClients/FACTORY/wasm/factory.wasm PAIR_WASM_PATH=JsClients/PAIR/wasm/pair-token.wasm ERC20_MASTER_KEY_PAIR_PATH=JsClients/ERC20/keys/ @@ -36,32 +36,34 @@ FACTORY_CONTRACT_NAME=Factory INSTALL_PAYMENT_AMOUNT=220000000000 -MINT_PAYMENT_AMOUNT=70000000000 +MINT_PAYMENT_AMOUNT=5000000000 +MINT_AMOUNT=50 -BURN_PAYMENT_AMOUNT=70000000000 +BURN_PAYMENT_AMOUNT=5000000000 +BURN_AMOUNT=10 -APPROVE_PAYMENT_AMOUNT=7000000000 +APPROVE_PAYMENT_AMOUNT=5000000000 APPROVE_AMOUNT=50 -TRANSFER_PAYMENT_AMOUNT=7000000000 +TRANSFER_PAYMENT_AMOUNT=5000000000 TRANSFER_AMOUNT=5 -TRANSFER_FROM_PAYMENT_AMOUNT=7000000000 +TRANSFER_FROM_PAYMENT_AMOUNT=5000000000 TRANSFER_FROM_AMOUNT=5 -SKIM_PAYMENT_AMOUNT=70000000000 +SKIM_PAYMENT_AMOUNT=5000000000 -SYNC_PAYMENT_AMOUNT=70000000000 +SYNC_PAYMENT_AMOUNT=5000000000 -SWAP_PAYMENT_AMOUNT=70000000000 +SWAP_PAYMENT_AMOUNT=5000000000 -INITIALIZE_PAYMENT_AMOUNT=70000000000 +INITIALIZE_PAYMENT_AMOUNT=5000000000 -SET_TREASURY_FEE_PERCENT_PAYMENT_AMOUNT=70000000000 +SET_TREASURY_FEE_PERCENT_PAYMENT_AMOUNT=5000000000 -SET_FEE_TO_PAYMENT_AMOUNT=20000000000 -SET_FEE_TO_SETTER_PAYMENT_AMOUNT=20000000000 -CREATE_PAIR_PAYMENT_AMOUNT=20000000000 +SET_FEE_TO_PAYMENT_AMOUNT=5000000000 +SET_FEE_TO_SETTER_PAYMENT_AMOUNT=5000000000 +CREATE_PAIR_PAYMENT_AMOUNT=5000000000 FACTORY_CONTRACT=c9d0268ecea8c57ed456bf56e4fba4bf285a4588fd817832230b8fd86b71c30f PAIR_CONTRACT=11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59 diff --git a/JsClients/ERC20/src/constants.ts b/JsClients/ERC20/src/constants.ts index 88d85ede..5bdf9782 100644 --- a/JsClients/ERC20/src/constants.ts +++ b/JsClients/ERC20/src/constants.ts @@ -1,12 +1,4 @@ export enum ERC20Events { - MintOne = "erc20_mint_one", - TransferToken = "erc20_transfer_token", - BurnOne = "erc20_burn_one", - MetadataUpdate = 'erc20_metadata_update', - Approve = 'approve', - Transfer = 'transfer', - TransferFrom = 'transfer_from', - Mint = 'mint', - Burn = 'burn', - Permit = 'permit', + Approval="approve", + Transfer="transfer" } diff --git a/JsClients/ERC20/src/erc20.ts b/JsClients/ERC20/src/erc20.ts index a67ca21f..fe10447a 100644 --- a/JsClients/ERC20/src/erc20.ts +++ b/JsClients/ERC20/src/erc20.ts @@ -25,16 +25,16 @@ class ERC20Client { private contractName: string = "erc20"; private contractHash: string= "erc20"; private contractPackageHash: string= "erc20"; - // private namedKeys: { - // balances:string; - // metadata: string; - // nonces: string; - // allowances: string; - // ownedTokens: string; - // owners: string; - // paused: string; + private namedKeys: { + balances:string + metadata: string; + nonces: string; + allowances: string; + ownedTokens: string; + owners: string; + paused: string; - // }; + }; private isListening = false; private pendingDeploys: IPendingDeploy[] = []; @@ -45,7 +45,18 @@ class ERC20Client { private chainName: string, private eventStreamAddress?: string, - ) { } + ) + { + this.namedKeys= { + balances:"null", + metadata: "null", + nonces: "null", + allowances: "null", + ownedTokens: "null", + owners: "null", + paused: "null" + }; + } public async install( keys: Keys.AsymmetricKey, @@ -146,7 +157,7 @@ class ERC20Client { const result = await utils.contractDictionaryGetter( this.nodeAddress, accountHash, - 'balances' + this.namedKeys.balances ); const maybeValue = result.value().unwrap(); return maybeValue.value().toString(); @@ -157,7 +168,7 @@ class ERC20Client { const result = await utils.contractDictionaryGetter( this.nodeAddress, accountHash, - 'nonces' + this.namedKeys.nonces ); const maybeValue = result.value().unwrap(); return maybeValue.value().toString(); @@ -170,7 +181,7 @@ class ERC20Client { const result = await utils.contractDictionaryGetter( this.nodeAddress, accountHash, - 'allowances' + this.namedKeys.allowances ); const maybeValue = result.value().unwrap(); return maybeValue.value().toString(); @@ -209,7 +220,7 @@ class ERC20Client { }); if (deployHash !== null) { - this.addPendingDeploy(ERC20Events.Approve, deployHash); + this.addPendingDeploy(ERC20Events.Approval, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -301,7 +312,7 @@ class ERC20Client { }); if (deployHash !== null) { - this.addPendingDeploy(ERC20Events.Mint, deployHash); + this.addPendingDeploy(ERC20Events.Transfer, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -331,7 +342,7 @@ class ERC20Client { }); if (deployHash !== null) { - this.addPendingDeploy(ERC20Events.Burn, deployHash); + this.addPendingDeploy(ERC20Events.Transfer, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -369,7 +380,7 @@ class ERC20Client { }); if (deployHash !== null) { - this.addPendingDeploy(ERC20Events.Permit, deployHash); + this.addPendingDeploy(ERC20Events.Approval, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); diff --git a/JsClients/ERC20/src/types.d.ts b/JsClients/ERC20/src/types.d.ts index 8f5fd913..af90b09b 100644 --- a/JsClients/ERC20/src/types.d.ts +++ b/JsClients/ERC20/src/types.d.ts @@ -1,4 +1,5 @@ import { CLAccountHash, CLByteArray, CLPublicKey } from "casper-js-sdk"; +import {ERC20Events} from "./constants"; export type RecipientType = CLPublicKey | CLAccountHash | CLByteArray; diff --git a/JsClients/ERC20/test/installed.ts b/JsClients/ERC20/test/installed.ts index c70f61e7..8044c757 100644 --- a/JsClients/ERC20/test/installed.ts +++ b/JsClients/ERC20/test/installed.ts @@ -43,26 +43,40 @@ const erc20 = new ERC20Client( EVENT_STREAM_ADDRESS! ); -const listener = erc20.onEvent( - [ - ERC20Events.Approve, - ERC20Events.Transfer, - ERC20Events.TransferFrom, - ERC20Events.Mint, - ], - (eventName, deploy, result) => { - if (deploy.success) { - console.log(`Successfull deploy of: ${eventName}, deployHash: ${deploy.deployHash}`); - console.log(result.value()); - } else { - console.log(`Failed deploy of ${eventName}, deployHash: ${deploy.deployHash}`); - console.log(`Error: ${deploy.error}`); +const test = async () => { + + const listener = erc20.onEvent( + [ + ERC20Events.Approval, + ERC20Events.Transfer + ], + async (eventName, deploy, result) => { + if (deploy.success) { + console.log(`Successfull deploy of: ${eventName}, deployHash: ${deploy.deployHash}`); + const [timestamp,gasPrice,block_hash]= await getDeploy(NODE_ADDRESS!, deploy.deployHash); + console.log("... Deployhash: ", deploy.deployHash); + console.log("... Timestamp: ", timestamp); + //console.log("... GasPrice: ", gasPrice); + console.log("... Block hash: ", block_hash); + + let newData = JSON.parse(JSON.stringify(result.value())); + + console.log(eventName+ " Event result: "); + console.log(newData[0][0].data + " = " + newData[0][1].data); + console.log(newData[1][0].data + " = " + newData[1][1].data); + console.log(newData[2][0].data + " = " + newData[2][1].data); + console.log(newData[3][0].data + " = " + newData[3][1].data); + console.log(newData[4][0].data + " = " + newData[4][1].data); + + + } else { + console.log(`Failed deploy of ${eventName}, deployHash: ${deploy.deployHash}`); + console.log(`Error: ${deploy.error}`); + } } - } -); + ); + console.log("listener: ",listener); -const test = async () => { - await sleep(5 * 1000); let accountInfo = await utils.getAccountInfo(NODE_ADDRESS!, KEYS.publicKey); @@ -101,13 +115,13 @@ const test = async () => { // console.log(`... Balance of account ${KEYS.publicKey.toAccountHashStr()}`); console.log(`... Balance: ${balance}`); - //balanceof + //nonce let nonce = await erc20.nonce(KEYS.publicKey); console.log(`... Nonce: ${nonce}`); - // //allowance - // let allowance = await erc20.allowance(KEYS.publicKey,KEYS.publicKey); - // console.log(`... Allowance: ${allowance}`); + // // //allowance + // // let allowance = await erc20.allowance(KEYS.publicKey,KEYS.publicKey); + // // console.log(`... Allowance: ${allowance}`); //mint const mintDeployHash = await erc20.mint( @@ -119,60 +133,61 @@ const test = async () => { console.log("... Mint deploy hash: ", mintDeployHash); await getDeploy(NODE_ADDRESS!, mintDeployHash); - console.log("... Token minted successfully"); - - //burn - const burnDeployHash = await erc20.burn( - KEYS, - KEYS.publicKey, - BURN_AMOUNT!, - BURN_PAYMENT_AMOUNT! - ); - console.log("... Burn deploy hash: ", burnDeployHash); - - await getDeploy(NODE_ADDRESS!, burnDeployHash); - console.log("... Token burned successfully"); - - //totalsupply - totalSupply = await erc20.totalSupply(); - console.log(`... Total supply: ${totalSupply}`); - - //approve - const approveDeployHash = await erc20.approve( - KEYS, - KEYS.publicKey, - APPROVE_AMOUNT!, - APPROVE_PAYMENT_AMOUNT! - ); - console.log("... Approve deploy hash: ", approveDeployHash); - - await getDeploy(NODE_ADDRESS!, approveDeployHash); - console.log("... Token approved successfully"); - - //transfer - const transferDeployHash = await erc20.transfer( - KEYS, - KEYS.publicKey, - TRANSFER_AMOUNT!, - TRANSFER_PAYMENT_AMOUNT! - ); - console.log("... Transfer deploy hash: ", transferDeployHash); - - await getDeploy(NODE_ADDRESS!, transferDeployHash); - console.log("... Token transfer successfully"); - - //transfer_from - const transferfromDeployHash = await erc20.transferFrom( - KEYS, - KEYS.publicKey, - KEYS.publicKey, - TRANSFER_FROM_AMOUNT!, - TRANSFER_FROM_PAYMENT_AMOUNT! - ); - console.log("... TransferFrom deploy hash: ", transferfromDeployHash); - - await getDeploy(NODE_ADDRESS!, transferfromDeployHash); - console.log("... Token transfer successfully"); + + + + // //burn + // const burnDeployHash = await erc20.burn( + // KEYS, + // KEYS.publicKey, + // BURN_AMOUNT!, + // BURN_PAYMENT_AMOUNT! + // ); + // console.log("... Burn deploy hash: ", burnDeployHash); + + // await getDeploy(NODE_ADDRESS!, burnDeployHash); + // console.log("... Token burned successfully"); + + // //totalsupply + // totalSupply = await erc20.totalSupply(); + // console.log(`... Total supply: ${totalSupply}`); + + // //approve + // const approveDeployHash = await erc20.approve( + // KEYS, + // KEYS.publicKey, + // APPROVE_AMOUNT!, + // APPROVE_PAYMENT_AMOUNT! + // ); + // console.log("... Approve deploy hash: ", approveDeployHash); + + // await getDeploy(NODE_ADDRESS!, approveDeployHash); + // console.log("... Token approved successfully"); + + // //transfer + // const transferDeployHash = await erc20.transfer( + // KEYS, + // KEYS.publicKey, + // TRANSFER_AMOUNT!, + // TRANSFER_PAYMENT_AMOUNT! + // ); + // console.log("... Transfer deploy hash: ", transferDeployHash); + + // await getDeploy(NODE_ADDRESS!, transferDeployHash); + // console.log("... Token transfer successfully"); + + // //transfer_from + // const transferfromDeployHash = await erc20.transferFrom( + // KEYS, + // KEYS.publicKey, + // KEYS.publicKey, + // TRANSFER_FROM_AMOUNT!, + // TRANSFER_FROM_PAYMENT_AMOUNT! + // ); + // console.log("... TransferFrom deploy hash: ", transferfromDeployHash); + + // await getDeploy(NODE_ADDRESS!, transferfromDeployHash); + // console.log("... Token transfer successfully"); }; diff --git a/JsClients/ERC20/test/utils.ts b/JsClients/ERC20/test/utils.ts index d258b38a..297be077 100644 --- a/JsClients/ERC20/test/utils.ts +++ b/JsClients/ERC20/test/utils.ts @@ -17,7 +17,8 @@ export const getDeploy = async (NODE_URL: string, deployHash: string) => { if (raw.execution_results.length !== 0){ // @ts-ignore if (raw.execution_results[0].result.Success) { - return deploy; + + return [deploy.header.timestamp,deploy.header.gasPrice,raw.execution_results[0].block_hash]; } else { // @ts-ignore throw Error("Contract execution: " + raw.execution_results[0].result.Failure.error_message); diff --git a/JsClients/ERC20/wasm/erc20-token.wasm b/JsClients/ERC20/wasm/erc20-token.wasm index 1ed4deda..08105c65 100644 Binary files a/JsClients/ERC20/wasm/erc20-token.wasm and b/JsClients/ERC20/wasm/erc20-token.wasm differ diff --git a/JsClients/FACTORY/src/constants.ts b/JsClients/FACTORY/src/constants.ts index 55a1156d..b1fca830 100644 --- a/JsClients/FACTORY/src/constants.ts +++ b/JsClients/FACTORY/src/constants.ts @@ -1,5 +1,3 @@ export enum FACTORYEvents { - SetFeeTo = "factory_set_fee_to", - SetFeeToSetter = "factory_set_fee_to_setter", - CreatePair = "factory_create_pair" + PairCreated="pair_created" } diff --git a/JsClients/FACTORY/src/factory.ts b/JsClients/FACTORY/src/factory.ts index 4b78dce6..e0f66fdc 100644 --- a/JsClients/FACTORY/src/factory.ts +++ b/JsClients/FACTORY/src/factory.ts @@ -154,7 +154,6 @@ class FACTORYClient { }); if (deployHash !== null) { - this.addPendingDeploy(FACTORYEvents.SetFeeTo, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -181,7 +180,6 @@ class FACTORYClient { }); if (deployHash !== null) { - this.addPendingDeploy(FACTORYEvents.SetFeeToSetter, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -217,7 +215,7 @@ class FACTORYClient { }); if (deployHash !== null) { - this.addPendingDeploy(FACTORYEvents.CreatePair, deployHash); + this.addPendingDeploy(FACTORYEvents.PairCreated, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); diff --git a/JsClients/FACTORY/test/install.ts b/JsClients/FACTORY/test/install.ts index 58d01bdc..eea3a93f 100644 --- a/JsClients/FACTORY/test/install.ts +++ b/JsClients/FACTORY/test/install.ts @@ -58,4 +58,4 @@ const test = async () => { console.log(`... Contract Hash: ${contractHash}`); }; -//test(); +test(); diff --git a/JsClients/FACTORY/test/installed.ts b/JsClients/FACTORY/test/installed.ts index 50bff459..93afdd1f 100644 --- a/JsClients/FACTORY/test/installed.ts +++ b/JsClients/FACTORY/test/installed.ts @@ -2,6 +2,7 @@ import { config } from "dotenv"; config(); import { FACTORYClient, utils, constants } from "../src"; import { parseTokenMeta, sleep, getDeploy } from "./utils"; +import { request } from 'graphql-request'; import { CLValueBuilder, @@ -38,25 +39,47 @@ const factory = new FACTORYClient( EVENT_STREAM_ADDRESS! ); -const listener = factory.onEvent( - [ - FACTORYEvents.SetFeeTo, - FACTORYEvents.SetFeeToSetter, - FACTORYEvents.CreatePair - ], - (eventName, deploy, result) => { - if (deploy.success) { - console.log(`Successfull deploy of: ${eventName}, deployHash: ${deploy.deployHash}`); - console.log(result.value()); - } else { - console.log(`Failed deploy of ${eventName}, deployHash: ${deploy.deployHash}`); - console.log(`Error: ${deploy.error}`); - } - } -); - const test = async () => { + const listener = factory.onEvent( + [ + FACTORYEvents.PairCreated + ], + async (eventName, deploy, result) => { + if (deploy.success) { + console.log(`Successfull deploy of: ${eventName}, deployHash: ${deploy.deployHash}`); + const [timestamp,gasPrice,block_hash]= await getDeploy(NODE_ADDRESS!, deploy.deployHash); + console.log("... Deployhash: ", deploy.deployHash); + console.log("... Timestamp: ", timestamp); + console.log("... Block hash: ", block_hash); + + let newData = JSON.parse(JSON.stringify(result.value())); + + console.log(eventName+ " Event result: "); + console.log(newData[0][0].data + " = " + newData[0][1].data); + console.log(newData[1][0].data + " = " + newData[1][1].data); + console.log(newData[2][0].data + " = " + newData[2][1].data); + console.log(newData[3][0].data + " = " + newData[3][1].data); + console.log(newData[4][0].data + " = " + newData[4][1].data); + console.log(newData[5][0].data + " = " + newData[5][1].data); + + request('http://localhost:3000/graphql', + `mutation handleNewPair( $token0: String!, $token1: String!, $pair: String!, $all_pairs_length: Int!, $timeStamp: Int!, $blockHash: String!){ + handleNewPair( token0: $token0, token1: $token1, pair: $pair, all_pairs_length: $all_pairs_length, timeStamp: $timeStamp, blockHash: $blockHash) { + id + } + + }`, + {token0:'51254d70d183f4b1e59ee5d5b0c76d3c3a81d0366278beecc05b546d49a9835c', token1: '96b0431770a34f5b651a43c830f3c8537e7c44f2cb8191d7efbcca2379785cda', pair: '11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59', all_pairs_length: 5, timeStamp:1000, blockHash:'0000000000000000000000000000000000000000000000000000000000000000'}) + .then(data => console.log(data)) + .catch(error => console.error(error)); + + } else { + console.log(`Failed deploy of ${eventName}, deployHash: ${deploy.deployHash}`); + console.log(`Error: ${deploy.error}`); + } + } + ); await sleep(5 * 1000); diff --git a/JsClients/FACTORY/test/utils.ts b/JsClients/FACTORY/test/utils.ts index 28564dd8..7fbbb15d 100644 --- a/JsClients/FACTORY/test/utils.ts +++ b/JsClients/FACTORY/test/utils.ts @@ -19,7 +19,7 @@ export const getDeploy = async (NODE_URL: string, deployHash: string) => { if (raw.execution_results.length !== 0) { // @ts-ignore if (raw.execution_results[0].result.Success) { - return deploy; + return [deploy.header.timestamp,deploy.header.gasPrice,raw.execution_results[0].block_hash]; } else { // @ts-ignore throw Error("Contract execution: " + raw.execution_results[0].result.Failure.error_message); diff --git a/JsClients/PAIR/src/constants.ts b/JsClients/PAIR/src/constants.ts index 43837875..188a6e6d 100644 --- a/JsClients/PAIR/src/constants.ts +++ b/JsClients/PAIR/src/constants.ts @@ -1,11 +1,8 @@ export enum PAIREvents { - Approve = 'approve', + Approval = 'approve', Transfer = 'transfer', - TransferFrom = 'transfer_from', Mint = 'mint', Burn = 'burn', - Permit = 'permit', - Skim = 'skim', Sync = 'sync', Swap = 'swap', diff --git a/JsClients/PAIR/src/pair.ts b/JsClients/PAIR/src/pair.ts index adb82b58..6fca2ad0 100644 --- a/JsClients/PAIR/src/pair.ts +++ b/JsClients/PAIR/src/pair.ts @@ -24,15 +24,15 @@ class PAIRClient { private contractName: string = "pair"; private contractHash: string= "pair"; private contractPackageHash: string= "pair"; - // private namedKeys: { - // balances: string; - // metadata: string; - // nonces: string; - // allowances: string; - // ownedTokens: string; - // owners: string; - // paused: string; - // }; + private namedKeys: { + balances: string; + metadata: string; + nonces: string; + allowances: string; + ownedTokens: string; + owners: string; + paused: string; + }; private isListening = false; private pendingDeploys: IPendingDeploy[] = []; @@ -40,7 +40,17 @@ class PAIRClient { private nodeAddress: string, private chainName: string, private eventStreamAddress?: string - ) { } + ) { + this.namedKeys= { + balances:"null", + metadata: "null", + nonces: "null", + allowances: "null", + ownedTokens: "null", + owners: "null", + paused: "null" + }; + } public async install( keys: Keys.AsymmetricKey, @@ -141,6 +151,7 @@ class PAIRClient { ); return result.value(); } + public async decimal() { const result = await contractSimpleGetter( this.nodeAddress, @@ -149,12 +160,13 @@ class PAIRClient { ); return result.value(); } + public async balanceOf(account: CLPublicKey) { const accountHash = Buffer.from(account.toAccountHash()).toString("hex"); const result = await utils.contractDictionaryGetter( this.nodeAddress, accountHash, - 'balances' + this.namedKeys.balances ); const maybeValue = result.value().unwrap(); return maybeValue.value().toString(); @@ -166,7 +178,7 @@ class PAIRClient { const result = await utils.contractDictionaryGetter( this.nodeAddress, accountHash, - 'nonces' + this.namedKeys.nonces ); const maybeValue = result.value().unwrap(); return maybeValue.value().toString(); @@ -179,7 +191,7 @@ class PAIRClient { const result = await utils.contractDictionaryGetter( this.nodeAddress, accountHash, - 'allowances' + this.namedKeys.allowances ); const maybeValue = result.value().unwrap(); return maybeValue.value().toString(); @@ -242,7 +254,7 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Approve, deployHash); + this.addPendingDeploy(PAIREvents.Approval, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -333,6 +345,7 @@ class PAIRClient { }); if (deployHash !== null) { + this.addPendingDeploy(PAIREvents.Sync, deployHash); this.addPendingDeploy(PAIREvents.Mint, deployHash); return deployHash; } else { @@ -346,7 +359,7 @@ class PAIRClient { ) { const runtimeArgs = RuntimeArgs.fromMap({ - from: utils.createRecipientAddress(to), + to: utils.createRecipientAddress(to), }); const deployHash = await contractCall({ @@ -360,6 +373,7 @@ class PAIRClient { }); if (deployHash !== null) { + this.addPendingDeploy(PAIREvents.Sync, deployHash); this.addPendingDeploy(PAIREvents.Burn, deployHash); return deployHash; } else { @@ -398,7 +412,7 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Permit, deployHash); + this.addPendingDeploy(PAIREvents.Approval, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -426,7 +440,6 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Skim, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -457,7 +470,7 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Mint, deployHash); + this.addPendingDeploy(PAIREvents.Transfer, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -520,6 +533,7 @@ class PAIRClient { if (deployHash !== null) { this.addPendingDeploy(PAIREvents.Sync, deployHash); + this.addPendingDeploy(PAIREvents.Swap, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -555,7 +569,6 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Approve, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -587,7 +600,7 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Mint, deployHash); + this.addPendingDeploy(PAIREvents.Transfer, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); @@ -616,7 +629,6 @@ class PAIRClient { }); if (deployHash !== null) { - this.addPendingDeploy(PAIREvents.Sync, deployHash); return deployHash; } else { throw Error("Invalid Deploy"); diff --git a/JsClients/PAIR/test/installed.ts b/JsClients/PAIR/test/installed.ts index b6a7aad4..f778f0a8 100644 --- a/JsClients/PAIR/test/installed.ts +++ b/JsClients/PAIR/test/installed.ts @@ -2,6 +2,7 @@ import { config } from "dotenv"; config(); import { PAIRClient, utils, constants } from "../src"; import { parseTokenMeta, sleep, getDeploy } from "./utils"; +import { request } from 'graphql-request'; import { CLValueBuilder, @@ -50,32 +51,57 @@ const pair = new PAIRClient( EVENT_STREAM_ADDRESS! ); -const listener = pair.onEvent( - [ - PAIREvents.Approve, - PAIREvents.Transfer, - PAIREvents.TransferFrom, - PAIREvents.Mint, - PAIREvents.Burn, - PAIREvents.Permit, - PAIREvents.Skim, - PAIREvents.Sync, - PAIREvents.Swap, - ], - (eventName, deploy, result) => { - if (deploy.success) { - console.log(`Successfull deploy of: ${eventName}, deployHash: ${deploy.deployHash}`); - console.log(result.value()); - } else { - console.log(`Failed deploy of ${eventName}, deployHash: ${deploy.deployHash}`); - console.log(`Error: ${deploy.error}`); - } - } -); - const test = async () => { + const listener = pair.onEvent( + [ + PAIREvents.Approval, + PAIREvents.Transfer, + PAIREvents.Mint, + PAIREvents.Burn, + PAIREvents.Sync, + PAIREvents.Swap, + ], + async (eventName, deploy, result) => { + if (deploy.success) { + console.log(`Successfull deploy of: ${eventName}, deployHash: ${deploy.deployHash}`); + const [timestamp,gasPrice,block_hash]= await getDeploy(NODE_ADDRESS!, deploy.deployHash); + console.log("... Deployhash: ", deploy.deployHash); + console.log("... Timestamp: ", timestamp); + //console.log("... GasPrice: ", gasPrice); + console.log("... Block hash: ", block_hash); + + let newData = JSON.parse(JSON.stringify(result.value())); + + console.log(eventName+ " Event result: "); + console.log(newData[0][0].data + " = " + newData[0][1].data); + console.log(newData[1][0].data + " = " + newData[1][1].data); + console.log(newData[2][0].data + " = " + newData[2][1].data); + console.log(newData[3][0].data + " = " + newData[3][1].data); + console.log(newData[4][0].data + " = " + newData[4][1].data); + console.log(newData[5][0].data + " = " + newData[5][1].data); + + // if(eventName=="transfer") + // { + // request('http://localhost:3000/graphql', `mutation handleTransfer($from: String!, $to: String!, $value: Int!, $pair: String!) { + // createUser(email: $email, password: $password) { + // id + // email + // } + // }`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'}) + // .then(data => console.info(data)) + // .catch(error => console.error(error)); + + // } + + } else { + console.log(`Failed deploy of ${eventName}, deployHash: ${deploy.deployHash}`); + console.log(`Error: ${deploy.error}`); + } + } + ); + await sleep(5 * 1000); let accountInfo = await utils.getAccountInfo(NODE_ADDRESS!, KEYS.publicKey); diff --git a/JsClients/PAIR/test/utils.ts b/JsClients/PAIR/test/utils.ts index 487cdcec..04e32d84 100644 --- a/JsClients/PAIR/test/utils.ts +++ b/JsClients/PAIR/test/utils.ts @@ -19,7 +19,7 @@ export const getDeploy = async (NODE_URL: string, deployHash: string) => { if (raw.execution_results.length !== 0) { // @ts-ignore if (raw.execution_results[0].result.Success) { - return deploy; + return [deploy.header.timestamp,deploy.header.gasPrice,raw.execution_results[0].block_hash]; } else { // @ts-ignore throw Error("Contract execution: " + raw.execution_results[0].result.Failure.error_message); diff --git a/JsClients/PAIR/wasm/pair-token.wasm b/JsClients/PAIR/wasm/pair-token.wasm index 250f1de4..aa070a29 100644 Binary files a/JsClients/PAIR/wasm/pair-token.wasm and b/JsClients/PAIR/wasm/pair-token.wasm differ diff --git a/graphql/dayUpdates.js b/graphql/dayUpdates.js index 125532e1..0810883d 100644 --- a/graphql/dayUpdates.js +++ b/graphql/dayUpdates.js @@ -15,14 +15,14 @@ const { } = require("./helpers"); -async function updateUniswapDayData (uniswapdaydata) { +async function updateUniswapDayData (timeStamp) { try { let uniswap = await UniswapFactory.findOne({ id: process.env.FACTORY_ADDRESS, }); //let timestamp = event.block.timestamp.toI32(); - let timestamp = 100000; + let timestamp = timeStamp; let dayID = timestamp / 86400; let dayStartTimestamp = dayID * 86400; let uniswapDayData = await UniswapDayData.findOne({ @@ -52,23 +52,22 @@ async function updateUniswapDayData (uniswapdaydata) { } -async function updatePairDayData (pairdaydata){ +async function updatePairDayData (timeStamp,pairAddress){ try { //let timestamp = event.block.timestamp.toI32(); - let timestamp = 100000; + let timestamp = timeStamp; let dayID = timestamp / 86400; let dayStartTimestamp = dayID * 86400; - let address = - "11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59"; + // let dayPairID = event.address // .toHexString() // .concat('-') // .concat(BigInt.fromI32(dayID).toString()); - let dayPairID = - "0000000000000000000000000000000000000000000000000000000000000000"; + + let dayPairID = pairAddress + "-" + dayID; //let pair = Pir.load(event.address.toHexString()); - let pair = await Pair.findOne({ id: address }); + let pair = await Pair.findOne({ id: pairAddress }); let pairDayData = await PairDayData.findOne({ id: dayPairID }); if (pairDayData === null) { pairDayData = new PairDayData({ @@ -77,7 +76,7 @@ async function updatePairDayData (pairdaydata){ token0: pair.token0, token1: pair.token1, //pairAddress : event.address.toHexString(), - pairAddress: address, + pairAddress: pairAddress, dailyVolumeToken0: ZERO_BD, dailyVolumeToken1: ZERO_BD, dailyVolumeUSD: ZERO_BD, @@ -99,31 +98,28 @@ async function updatePairDayData (pairdaydata){ } -async function updatePairHourData (pairhourdata){ +async function updatePairHourData (timeStamp,pairAddress){ try { //let timestamp = event.block.timestamp.toI32(); - let timestamp = 100000; + let timestamp = timeStamp; let hourIndex = timestamp / 3600; // get unique hour within unix history let hourStartUnix = hourIndex * 3600; // want the rounded effect - let address = - "11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59"; + // let hourPairID = event.address // .toHexString() // .concat('-') // .concat(BigInt.fromI32(hourIndex).toString()); - let hourPairID = - "0000000000000000000000000000000000000000000000000000000000000000"; - + let hourPairID = pairAddress + "-" + hourIndex; //let pair = Pair.load(event.address.toHexString()) - let pair = await Pair.findOne({ id: address }); + let pair = await Pair.findOne({ id: pairAddress }); let pairHourData = await PairHourData.findOne({ id: hourPairID }); if (pairHourData === null) { pairHourData = new PairHourData({ id: hourPairID, hourStartUnix: hourStartUnix, //pair : event.address.toHexString(), - pair: address, + pair: pairAddress, hourlyVolumeToken0: ZERO_BD, hourlyVolumeToken1: ZERO_BD, hourlyVolumeUSD: ZERO_BD, @@ -145,11 +141,11 @@ async function updatePairHourData (pairhourdata){ } -async function updateTokenDayData (token,tokendaydata) { +async function updateTokenDayData (token,timeStamp) { try { let bundle = await Bundle.findOne({ id: "1" }); //let timestamp = event.block.timestamp.toI32(); - let timestamp = 100000; + let timestamp = timeStamp; let dayID = timestamp / 86400; let dayStartTimestamp = dayID * 86400; // let tokenDayID = args.token @@ -157,16 +153,16 @@ async function updateTokenDayData (token,tokendaydata) { // .concat("-") // .concat(BigInt.fromI32(dayID).toString()); - let tokenDayID = token; + let tokenDayID = token.id+ "-"+ dayID.toString(); //let tokenDayData = TokenDayData.load(tokenDayID); let tokenDayData = await TokenDayData.findOne({ id: tokenDayID }); - let tokendata = await Token.findOne({ id: token }); + let tokendata = await Token.findOne({ id: token.id }); if (tokenDayData === null) { tokenDayData = new TokenDayData({ id: tokenDayID, date: dayStartTimestamp, - token: token, + token: token.id, priceUSD: tokendata.derivedETH * bundle.ethPrice, dailyVolumeToken: ZERO_BD, dailyVolumeETH: ZERO_BD, diff --git a/graphql/helpers.js b/graphql/helpers.js index 12a3aa9b..dbd68e8a 100644 --- a/graphql/helpers.js +++ b/graphql/helpers.js @@ -10,7 +10,7 @@ const Bundle = require("../models/bundle"); require("dotenv").config(); const ADDRESS_ZERO = - "account-hash-0000000000000000000000000000000000000000000000000000000000000000"; + "0000000000000000000000000000000000000000000000000000000000000000"; let ZERO_BI = 0; let ONE_BI = 1; @@ -155,14 +155,14 @@ async function createLiquidityPosition(exchange, user, value) { try { // let liquidityTokenBalance = await LiquidityPosition.findOne({id: exchange.toHexString().concat('-').concat(user.toHexString())}); let liquidityTokenBalance = await LiquidityPosition.findOne({ - id: exchange + " - " + user, + id: exchange + "-" + user, }); if (liquidityTokenBalance === null) { let pair = await Pair.findOne({ id: exchange }); pair.liquidityProviderCount = pair.liquidityProviderCount + ONE_BI; liquidityTokenBalance = new LiquidityPosition({ // id:exchange.toHexString().concat('-').concat(user.toHexString()), - id: exchange + " - " + user, + id: exchange + "-" + user, liquidityTokenBalance: value, pair: exchange, user: user, @@ -195,7 +195,7 @@ async function createUser(address) { } } -async function createLiquiditySnapshot(position, event) { +async function createLiquiditySnapshot(position, timeStamp, blockHash) { try { // let timestamp = event.block.timestamp.toI32(); let timestamp = 1000; @@ -208,11 +208,11 @@ async function createLiquiditySnapshot(position, event) { // create new snapshot let snapshot = new LiquidityPositionSnapshot({ // id:position.id.concat(timestamp.toString()), - id: position.id + timestamp.toString(), + id: position.id + timeStamp.toString(), liquidityPosition: position.id, - timestamp: timestamp, - // block : event.block.number.toI32(), - block: 599, + timestamp: timeStamp, + block : blockHash, + // block: 599, user: position.user, pair: position.pair, token0PriceUSD: token0.derivedETH * bundle.ethPrice, diff --git a/graphql/mutations.js b/graphql/mutations.js index fc0b7a64..1a2dea59 100644 --- a/graphql/mutations.js +++ b/graphql/mutations.js @@ -23,6 +23,7 @@ let uniswapDayData = require("../models/uniswapDayData"); let token0DayData = require("../models/tokenDayData"); let token1DayData = require("../models/tokenDayData"); +const {bundleType} = require("./types/bundle"); const { fetchTokenDecimals, fetchTokenName, @@ -57,12 +58,18 @@ const { getTrackedVolumeUSD, getTrackedLiquidityUSD, } = require("./pricing"); +const bundle = require("../models/bundle"); const handleNewPair = { - type: GraphQLBoolean, + type: bundleType, description: "Handle New Pair", args: { - PairCreated: { type: GraphQLBoolean }, + token0: { type: GraphQLString }, + token1: { type:GraphQLString }, + pair: { type: GraphQLString }, + all_pairs_length: { type: GraphQLInt }, + timeStamp: { type: GraphQLInt }, + blockHash: { type: GraphQLString } }, async resolve(parent, args, context) { try { @@ -97,12 +104,12 @@ const handleNewPair = { // let token1 = Token.load(event.params.token1.toHexString()); // create the tokens - let token0 = await Token.findOne({ id: process.env.token0 }); - let token1 = await Token.findOne({ id: process.env.token1 }); + let token0 = await Token.findOne({ id: args.token0 }); + let token1 = await Token.findOne({ id: args.token1 }); // fetch info if null if (token0 === null) { - let Decimals = await fetchTokenDecimals(process.env.token0); + let Decimals = await fetchTokenDecimals(args.token0); // bail if we couldn't figure out the decimals if (Decimals === null) { @@ -110,12 +117,12 @@ const handleNewPair = { return; } - let TokenName=await fetchTokenName(process.env.token0); - let TokenSymbol=await fetchTokenSymbol(process.env.token0); - let TokenTotalSupply=await fetchTokenTotalSupply(process.env.token0); + let TokenName=await fetchTokenName(args.token0); + let TokenSymbol=await fetchTokenSymbol(args.token0); + let TokenTotalSupply=await fetchTokenTotalSupply(args.token0); token0 = new Token({ - id: process.env.token0, + id: args.token0, symbol: TokenSymbol, name: TokenName, totalSupply:TokenTotalSupply, @@ -131,19 +138,19 @@ const handleNewPair = { // fetch info if null if (token1 === null) { - let Decimals = await fetchTokenDecimals(process.env.token1); + let Decimals = await fetchTokenDecimals(args.token1); // bail if we couldn't figure out the decimals if (Decimals === null) { return; } - let TokenName=await fetchTokenName(process.env.token1); - let TokenSymbol=await fetchTokenSymbol(process.env.token1); - let TokenTotalSupply=await fetchTokenTotalSupply(process.env.token1); + let TokenName=await fetchTokenName(args.token1); + let TokenSymbol=await fetchTokenSymbol(args.token1); + let TokenTotalSupply=await fetchTokenTotalSupply(args.token1); token1 = new Token({ - id: process.env.token1, + id: args.token1, symbol: TokenSymbol, name: TokenName, totalSupply:TokenTotalSupply, @@ -158,14 +165,12 @@ const handleNewPair = { } let pair = new Pair({ - id: process.env.pair, + id: args.pair, token0: token0.id, token1: token1.id, liquidityProviderCount: ZERO_BI, - - //createdAtTimestamp : event.block.timestamp, - //createdAtBlockNumber : event.block.number, - + createdAtTimestamp : args.timeStamp, + createdAtBlockNumber :args.blockHash, txCount: ZERO_BI, reserve0: ZERO_BD, reserve1: ZERO_BD, @@ -189,8 +194,9 @@ const handleNewPair = { await token1.save(); await pair.save(); await factory.save(); - - return true; + + let bundle = await Bundle.findOne({ id: "1" }); + return bundle; } catch (error) { throw new Error(error); } @@ -208,13 +214,16 @@ async function isCompleteMint(mintId) { } const handleTransfer = { - type: GraphQLBoolean, + type: bundleType, description: "handle Transfer ", args: { - Transfer: { type: GraphQLBoolean }, - to: { type: GraphQLString }, + pairAddress: { type: GraphQLString }, from: { type: GraphQLString }, + to: { type: GraphQLString }, value: { type: GraphQLInt }, + deployHash: { type: GraphQLString }, + timeStamp: { type: GraphQLInt }, + blockHash: { type: GraphQLString } }, async resolve(parent, args, context) { try { @@ -235,7 +244,7 @@ const handleTransfer = { }); // let transactionHash = event.transaction.hash.toHexString(); - let transactionHash = "sampletransactionHash"; + let transactionHash = args.deployHash; // user stats //let from = event.params.from; @@ -246,11 +255,10 @@ const handleTransfer = { let to = args.to; createUser(to); - let address = - "hash-0000000000000000000000000000000000000000000000000000000000000000"; + //let address ="hash-0000000000000000000000000000000000000000000000000000000000000000"; // get pair and load contract //let pair = await Pair.findOne({ id: event.address.toHexString() }); - let pair = await Pair.findOne({ id: address }); + let pair = await Pair.findOne({ id: args.pairAddress }); //let pairContract = PairContract.bind(event.address); @@ -262,10 +270,10 @@ const handleTransfer = { if (transaction === null) { transaction = new Transaction({ id: transactionHash, - // blockNumber: event.block.number, - // timestamp: event.block.timestamp, - blockNumber: 599, - timestamp: 1222, + blockNumber: args.blockHash, + timestamp: args.timeStamp, + //blockNumber: 599, + //timestamp: 1222, mints: [], burns: [], swaps: [], @@ -286,7 +294,8 @@ const handleTransfer = { // .toHexString() // .concat("-") // .concat(BigInt.fromI32(mints.length).toString()), - id: transactionHash, + id: transactionHash + "-" + mints.length, + //id: transactionHash, transaction: transaction.id, pair: pair.id, to: to, @@ -314,7 +323,8 @@ const handleTransfer = { // .toHexString() // .concat("-") // .concat(BigInt.fromI32(burns.length).toString()), - id: transactionHash, + id: transactionHash + "-" + burns.length, + //id: transactionHash, transaction: transaction.id, pair: pair.id, liquidity: args.value, @@ -356,7 +366,8 @@ const handleTransfer = { // .toHexString() // .concat("-") // .concat(BigInt.fromI32(burns.length).toString()), - id: transactionHash, + id: transactionHash + "-" + burns.length, + //id: transactionHash, transaction: transaction.id, needsComplete: false, pair: pair.id, @@ -371,7 +382,8 @@ const handleTransfer = { // .toHexString() // .concat("-") // .concat(BigInt.fromI32(burns.length).toString()), - id: transactionHash, + id: transactionHash + "-" + burns.length, + //id: transactionHash, transaction: transaction.id, needsComplete: false, pair: pair.id, @@ -415,33 +427,36 @@ const handleTransfer = { if (from != ADDRESS_ZERO && from != pair.id) { //let Balance =await PairContract.balanceOf(event.address,from); - createLiquidityPosition(address, from, args.value); + let Balance =await PairContract.balanceOf(args.pairAddress,from); + createLiquidityPosition(args.pairAddress, from, Balance); let fromUserLiquidityPosition = null; while (fromUserLiquidityPosition == null) { fromUserLiquidityPosition = await LiquidityPosition.findOne({ - id: address + " - " + from, + id: args.pairAddress + "-" + from, }); } - createLiquiditySnapshot(fromUserLiquidityPosition, "event"); + createLiquiditySnapshot(fromUserLiquidityPosition, args.timeStamp,args.blockHash); } if (to != ADDRESS_ZERO && to != pair.id) { //let Balance = await PairContract.balanceOf(event.address,to); - createLiquidityPosition(address, to, args.value); + let Balance = await PairContract.balanceOf(args.pairAddress,to); + createLiquidityPosition(args.pairAddress, to, Balance); let toUserLiquidityPosition = null; while (toUserLiquidityPosition == null) { toUserLiquidityPosition = await LiquidityPosition.findOne({ - id: address + " - " + to, + id: args.pairAddress + "-" + to, }); } - createLiquiditySnapshot(toUserLiquidityPosition, "event"); + createLiquiditySnapshot(toUserLiquidityPosition, args.timeStamp,args.blockHash); } await transaction.save(); - return true; + let bundle = await Bundle.findOne({ id: "1" }); + return bundle; } catch (error) { throw new Error(error); } @@ -453,13 +468,15 @@ const handleSync = { description: "handle Sync", args: { Sync: { type: GraphQLBoolean }, + pairAddress: { type: GraphQLString }, + reserve0: { type: GraphQLString }, + reserve1: { type: GraphQLString }, }, async resolve(parent, args, context) { try { - let address = - "hash-0000000000000000000000000000000000000000000000000000000000000000"; + //let address ="hash-0000000000000000000000000000000000000000000000000000000000000000"; // let pair = await Pair.findOne({ id: event.address.toHex() }); - let pair = await Pair.findOne({ id: address }); + let pair = await Pair.findOne({ id: args.pairAddress }); let token0 = await Token.findOne({ id: pair.token0 }); let token1 = await Token.findOne({ id: pair.token1 }); let uniswap = await UniswapFactory.findOne({ @@ -483,6 +500,9 @@ const handleSync = { // token1.decimals // ); + pair.reserve0 = args.reserve0; + pair.reserve1 = args.reserve1; + if (pair.reserve1 != ZERO_BD) pair.token0Price = pair.reserve0 / pair.reserve1; else pair.token0Price = ZERO_BD; @@ -500,8 +520,8 @@ const handleSync = { // token0.derivedETH = findEthPerToken(token0); // token1.derivedETH = findEthPerToken(token1); - token0.derivedETH = 0; - token1.derivedETH = 0; + token0.derivedETH = 0; //passing zero Because Casper don't have the feature right now + token1.derivedETH = 0; //passing zero Because Casper don't have the feature right now await token0.save(); await token1.save(); @@ -511,7 +531,7 @@ const handleSync = { // trackedLiquidityETH = // getTrackedLiquidityUSD(pair.reserve0, token0, pair.reserve1, token1) / // bundle.ethPrice; - trackedLiquidityETH = 0; + trackedLiquidityETH = 0; //passing zero Because Casper don't have the feature right now } else { trackedLiquidityETH = ZERO_BD; } @@ -547,11 +567,14 @@ const handleMint = { type: GraphQLBoolean, description: "handle Mint", args: { - Mint: { type: GraphQLBoolean }, amount0: { type: GraphQLInt }, amount1: { type: GraphQLInt }, sender: { type: GraphQLString }, - logIndex: { type: GraphQLInt }, + deployHash:{ type: GraphQLString}, + pairAddress:{ type: GraphQLString}, + timeStamp: { type: GraphQLInt }, + blockHash: { type: GraphQLString }, + logIndex: { type: GraphQLInt }, //we don't have logIndex in Casper yet }, async resolve(parent, args, context) { try { @@ -559,7 +582,7 @@ const handleMint = { // id: event.transaction.hash.toHexString(), // }); - let transactionHash = "sampletransactionHash"; + let transactionHash = args.deployHash; let transaction = await Transaction.findOne({ id: transactionHash, }); @@ -572,9 +595,8 @@ const handleMint = { if (mint === null) { return false; } - let address = - "0000000000000000000000000000000000000000000000000000000000000000"; - let pair = await Pair.findOne({ id: address }); + //let address ="0000000000000000000000000000000000000000000000000000000000000000"; + let pair = await Pair.findOne({ id: args.pairAddress }); let uniswap = await UniswapFactory.findOne({ id: process.env.FACTORY_ADDRESS, }); @@ -626,14 +648,14 @@ const handleMint = { await mint.save(); // update the LP position - createLiquidityPosition(address, mint.to); + createLiquidityPosition(args.pairAddress, mint.to); let liquidityPosition = null; while (liquidityPosition == null) { liquidityPosition = await LiquidityPosition.findOne({ - id: address + " - " + mint.to, + id: args.pairAddress + "-" + mint.to, }); } - createLiquiditySnapshot(liquidityPosition, "event"); + createLiquiditySnapshot(liquidityPosition, args.timeStamp.args.blockHash); // update day entities //updatePairDayData(event); @@ -642,11 +664,11 @@ const handleMint = { //updateTokenDayData(token0); //updateTokenDayData(token1); - updatePairDayData(true); - updatePairHourData(true); - updateUniswapDayData(true); - updateTokenDayData(process.env.token0,true); - updateTokenDayData(process.env.token1,true); + updatePairDayData(args.timeStamp,args.pairAddress); + updatePairHourData(args.timeStamp,args.pairAddress); + updateUniswapDayData(args.timeStamp); + updateTokenDayData(token0,args.timeStamp); + updateTokenDayData(token1,args.timeStamp); return true; } catch (error) { @@ -659,18 +681,22 @@ const handleBurn = { type: GraphQLBoolean, description: "handle Burn", args: { - Burn: { type: GraphQLBoolean }, amount0: { type: GraphQLInt }, amount1: { type: GraphQLInt }, sender: { type: GraphQLString }, - logIndex: { type: GraphQLInt }, + deployHash:{ type: GraphQLString}, + pairAddress:{ type: GraphQLString}, + timeStamp: { type: GraphQLInt }, + blockHash: { type: GraphQLString }, + logIndex: { type: GraphQLInt }, //we don't have logIndex in Casper yet + to: { type: GraphQLString} }, async resolve(parent, args, context) { try { // let transaction = await Transaction.findOne({ // id: event.transaction.hash.toHexString(), // }); - let transactionHash = "sampletransactionHash"; + let transactionHash = args.deployHash; let transaction = await Transaction.findOne({ id: transactionHash, }); @@ -684,9 +710,8 @@ const handleBurn = { if (burn === null) { return false; } - let address = - "0000000000000000000000000000000000000000000000000000000000000000"; - let pair = await Pair.findOne({ id: address }); + //let address ="0000000000000000000000000000000000000000000000000000000000000000"; + let pair = await Pair.findOne({ id: args.pairAaddress }); let uniswap = await UniswapFactory.findOne({ id: process.env.FACTORY_ADDRESS, }); @@ -732,19 +757,20 @@ const handleBurn = { burn.amount0 = token0Amount; burn.amount1 = token1Amount; // burn.to = event.params.to + burn.to = args.to; burn.logIndex = args.logIndex; burn.amountUSD = amountTotalUSD; await burn.save(); // update the LP position - createLiquidityPosition(address, burn.sender); + createLiquidityPosition(args.pairAddress, burn.sender); let liquidityPosition = null; while (liquidityPosition == null) { liquidityPosition = await LiquidityPosition.findOne({ - id: address + " - " + burn.sender, + id: args.pairAddress + "-" + burn.sender, }); } - createLiquiditySnapshot(liquidityPosition, "event"); + createLiquiditySnapshot(liquidityPosition, args.timeStamp,args.blockHash); // update day entities //updatePairDayData(event); @@ -753,11 +779,11 @@ const handleBurn = { //updateTokenDayData(token0, event); //updateTokenDayData(token1, event); - updatePairDayData(true); - updatePairHourData(true); - updateUniswapDayData(true); - updateTokenDayData(process.env.token0,true); - updateTokenDayData(process.env.token1,true); + updatePairDayData(args.timeStamp,args.pairAddress); + updatePairHourData(args.timeStamp,args.pairAddress); + updateUniswapDayData(args.timeStamp); + updateTokenDayData(token0,args.timeStamp); + updateTokenDayData(token1,args.timeStamp); return true; } catch (error) { @@ -770,21 +796,23 @@ const handleSwap = { type: GraphQLBoolean, description: "handle Swap", args: { - Swap: { type: GraphQLBoolean }, amount0In: { type: GraphQLInt }, amount1In: { type: GraphQLInt }, amount0Out: { type: GraphQLInt }, amount1Out: { type: GraphQLInt }, + deployHash:{ type: GraphQLString}, + pairAddress:{ type: GraphQLString}, + timeStamp: { type: GraphQLInt }, + blockHash: { type: GraphQLString }, to: { type: GraphQLString }, from: { type: GraphQLString }, sender: { type: GraphQLString }, - logIndex: { type: GraphQLInt }, + logIndex: { type: GraphQLInt } //we don't have logIndex in Casper yet }, async resolve(parent, args, context) { try { // let pair = await Pair.findOne({ id: event.address.toHexString() }); - let address="11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59"; - let pair = await Pair.findOne({ id: address }); + let pair = await Pair.findOne({ id: args.pairAddress }); let token0 = await Token.findOne({ id: pair.token0 }); let token1 = await Token.findOne({ id: pair.token1 }); @@ -831,7 +859,7 @@ const handleSwap = { // token1, // pair // ); - let trackedAmountUSD = 0; + let trackedAmountUSD = 0; //passing zero Because Casper don't have the feature right now let trackedAmountETH; if (bundle.ethPrice == ZERO_BD) { @@ -881,7 +909,7 @@ const handleSwap = { // let transaction = await Transaction.fineOne({ // id: event.transaction.hash.toHexString(), // }); - let transactionHash = "sampletransactionHash"; + let transactionHash = args.deployHash; let transaction = await Transaction.findOne({ id: transactionHash, }); @@ -889,10 +917,10 @@ const handleSwap = { transaction = new Transaction({ // id: event.transaction.hash.toHexString(), id: transactionHash, - // blockNumber: event.block.number, - // timestamp: event.block.timestamp, - blockNumber: 499, - timestamp: 1334, + blockNumber: args.blockHash, + timestamp: args.timeStamp, + //blockNumber: 499, + //timestamp: 1334, mints: [], swaps: [], burns: [], @@ -904,7 +932,8 @@ const handleSwap = { // .toHexString() // .concat("-") // .concat(BigInt.fromI32(swaps.length).toString()), - id: transactionHash, + id: transactionHash+ "-"+ (swaps.length), + //id: transactionHash, // update swap event transaction: transaction.id, pair: pair.id, @@ -943,11 +972,11 @@ const handleSwap = { // let token0DayData = updateTokenDayData(token0, event); // let token1DayData = updateTokenDayData(token1, event); - pairDayData = await updatePairDayData(true); - pairHourData = await updatePairHourData(true); - uniswapDayData = await updateUniswapDayData(true); - token0DayData = await updateTokenDayData(process.env.token0, true); - token1DayData = await updateTokenDayData(process.env.token1, true); + pairDayData = await updatePairDayData(args.timeStamp,args.pairAddress); + pairHourData = await updatePairHourData(args.timeStamp,args.pairAddress); + uniswapDayData = await updateUniswapDayData(args.timeStamp); + token0DayData = await updateTokenDayData(token0,args.timeStamp); + token1DayData = await updateTokenDayData(token1,args.timeStamp); // swap specific updating uniswapDayData.dailyVolumeUSD = diff --git a/package-lock.json b/package-lock.json index 15df1ba5..95ee66d1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -534,6 +534,11 @@ "safer-buffer": "^2.1.0" } }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, "balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -942,6 +947,14 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "requires": { + "delayed-stream": "~1.0.0" + } + }, "commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", @@ -1039,6 +1052,21 @@ "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==" }, + "cross-fetch": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.4.tgz", + "integrity": "sha512-1eAtFWdIubi6T4XPy6ei9iUFoKpUkIF971QLN8lIvvvwueI65+Nw5haMNKUwfJxabqlIIDODJKGrQ66gxC0PbQ==", + "requires": { + "node-fetch": "2.6.1" + }, + "dependencies": { + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==" + } + } + }, "crypto-random-string": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", @@ -1094,6 +1122,11 @@ "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.3.tgz", "integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==" }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" + }, "denque": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/denque/-/denque-2.0.1.tgz", @@ -1458,6 +1491,11 @@ } } }, + "extract-files": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/extract-files/-/extract-files-9.0.0.tgz", + "integrity": "sha512-CvdFfHkC95B4bBBk36hcEmvdR2awOdhhVUYH6S/zrVj3477zven/fJMYg7121h4T1xHZC+tetUpubpAhxwI7hQ==" + }, "fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -1501,6 +1539,16 @@ "unpipe": "~1.0.0" } }, + "form-data": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", + "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, "forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -1602,6 +1650,16 @@ "resolved": "https://registry.npmjs.org/graphql/-/graphql-15.6.1.tgz", "integrity": "sha512-3i5lu0z6dRvJ48QP9kFxBkJ7h4Kso7PS8eahyTFz5Jm6CvQfLtNIE8LX9N6JLnXTuwR+sIYnXzaWp6anOg0QQw==" }, + "graphql-request": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/graphql-request/-/graphql-request-3.6.1.tgz", + "integrity": "sha512-Nm1EasrAQVZllyNTlHDLnLZjlhC6eRWnWP6KH//ytnAL08pjlLkdI2K+s6OV92p45hn5b/kUlLbDwACmRoLwrQ==", + "requires": { + "cross-fetch": "^3.0.6", + "extract-files": "^9.0.0", + "form-data": "^3.0.0" + } + }, "has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", diff --git a/package.json b/package.json index 895badc1..c8c80a33 100644 --- a/package.json +++ b/package.json @@ -4,26 +4,32 @@ "private": true, "scripts": { "start": "ts-node ./bin/www", - "test:install": "ts-node JsClients/ERC20/test/install.ts" + "test:erc20install": "ts-node JsClients/ERC20/test/install.ts", + "test:erc20installed": "ts-node JsClients/ERC20/test/installed.ts", + "test:pairinstall": "ts-node JsClients/PAIR/test/install.ts", + "test:pairinstalled": "ts-node JsClients/PAIR/test/installed.ts", + "test:factoryinstall": "ts-node JsClients/FACTORY/test/install.ts", + "test:factoryinstalled": "ts-node JsClients/FACTORY/test/installed.ts" }, "dependencies": { + "casper-js-sdk": "2.4.1", "cookie-parser": "~1.4.4", "debug": "~2.6.9", + "dotenv": "^10.0.0", "express": "~4.16.1", "express-graphql": "^0.12.0", "graphql": "^15.6.0", + "graphql-request": "^3.6.1", "http-errors": "~1.6.3", "jade": "~1.11.0", "mongoose": "^6.0.8", "morgan": "~1.9.1", - "casper-js-sdk": "2.4.1", - "ts-results": "^3.3.0", - "dotenv": "^10.0.0", + "nodemon": "^2.0.13", "prettier": "^2.3.2", "ts-node": "^10.1.0", + "ts-results": "^3.3.0", "tslint": "^5.12.1", "tslint-config-prettier": "^1.18.0", - "typescript": "^3.3.3", - "nodemon": "^2.0.13" + "typescript": "^3.3.3" } } diff --git a/test.js b/test.js index 7222d1ef..6c7921fa 100644 --- a/test.js +++ b/test.js @@ -1,22 +1,71 @@ -var mongoose = require('mongoose'); -require('mongoose-bigdecimal'); -var Schema = mongoose.Schema; -var BigDecimal = require('big.js'); - -//define your schema -var ProductSchema = new Schema({ - price: { - type: Schema.Types.BigDecimal, - required: true, - index:true - }, - discounts:[{ - type: Schema.Types.BigDecimal - }] -}); -Product = mongoose.model('Product', ProductSchema); - -//use it -var book = new Product(); -book.price = new BigDecimal(12); -book.save(done); \ No newline at end of file +// var mongoose = require('mongoose'); +// require('mongoose-bigdecimal'); +// var Schema = mongoose.Schema; +// var BigDecimal = require('big.js'); + +// //define your schema +// var ProductSchema = new Schema({ +// price: { +// type: Schema.Types.BigDecimal, +// required: true, +// index:true +// }, +// discounts:[{ +// type: Schema.Types.BigDecimal +// }] +// }); +// Product = mongoose.model('Product', ProductSchema); + +// //use it +// var book = new Product(); +// book.price = new BigDecimal(12); +// book.save(done); +// var data=[ +// [ +// { data: 'contract_package_hash' }, +// { +// data: '0024dc4c2ea77a01a0da90893c3283cfa602d78acf198aaa67e61e9bc9b44c93' +// } +// ], +// [ { data: 'event_type' }, { data: 'transfer' } ], +// [ +// { data: 'from' }, +// { +// data: 'Key::Account(0000000000000000000000000000000000000000000000000000000000000000)' +// } +// ], +// [ +// { data: 'to' }, +// { +// data: 'Key::Account(e56a24ed039010d56c2f47aad13fb740b94f3253889500129421054ebb38d917)' +// } +// ], +// [ { data: 'value' }, { data: '50' } ] +// ]; + +// console.log("data: ",data[0][1].data); + +const { request } = require('graphql-request'); + +// request('http://localhost:3000/graphql', +// `mutation handleTransfer( $pairAddress: String!, $from: String!, $to: String!, $value: Int!, $deployHash: String!, $timeStamp: Int!, $blockHash: String!){ +// handleTransfer( pairAddress: $pairAddress, from: $from, to: $to, value: $value, deployHash: $deployHash, timeStamp: $timeStamp, blockHash: $blockHash) { +// id +// } + +// }`, +// {pairAddress:'11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59', from: '0000000000000000000000000000000000000000000000000000000000000000', to: '0000000000000000000000000000000000000000000000000000000000000111', value: 5, pairAddress:'11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59', deployHash:'0000000000000000000000000000000000000000000000000000000000000000', timeStamp:1000, blockHash:'0000000000000000000000000000000000000000000000000000000000000000'}) +// .then(data => console.log(data)) +// .catch(error => console.error(error)); + +request('http://localhost:3000/graphql', + `mutation handleNewPair( $token0: String!, $token1: String!, $pair: String!, $all_pairs_length: Int!, $timeStamp: Int!, $blockHash: String!){ + handleNewPair( token0: $token0, token1: $token1, pair: $pair, all_pairs_length: $all_pairs_length, timeStamp: $timeStamp, blockHash: $blockHash) { + id + } + + }`, + {token0:'51254d70d183f4b1e59ee5d5b0c76d3c3a81d0366278beecc05b546d49a9835c', token1: '96b0431770a34f5b651a43c830f3c8537e7c44f2cb8191d7efbcca2379785cda', pair: '11f6e1b2d9566ab6d796f026b1d4bd36b71664c4ee8805fbc9cdca406607cd59', all_pairs_length: 5, timeStamp:1000, blockHash:'0000000000000000000000000000000000000000000000000000000000000000'}) + .then(data => console.log(data)) + .catch(error => console.error(error)); +