86 lines
2.5 KiB
JavaScript
86 lines
2.5 KiB
JavaScript
import {ethers, keccak256} from "ethers";
|
|
import {getAbi} from "./abi.js";
|
|
import {getSigner} from "./blockchain.js";
|
|
import {Cache} from './cache.js';
|
|
import vaultCode from 'contract/out/Vault.sol/Vault.json'
|
|
import assert from "assert";
|
|
import fs from 'fs';
|
|
import {ALL_CHAINS} from "./misc.js";
|
|
|
|
const VAULT_INIT_CODE_HASH = keccak256(vaultCode.bytecode.object)
|
|
|
|
console.log(VAULT_INIT_CODE_HASH)
|
|
|
|
const deployerAddresses = {}
|
|
|
|
for (const chainId of ALL_CHAINS) {
|
|
const path = `contract/broadcast/Deploy.sol/${chainId}/run-${process.env['DEXORDER_DEPLOYMENT_' + chainId]}.json`;
|
|
const deployment = JSON.parse(fs.readFileSync(path, 'utf8')) // synchronous is ok we only do this once on init
|
|
assert(deployment.transactions[0].contractName === 'VaultDeployer')
|
|
deployerAddresses[chainId] = deployment.transactions[0].contractAddress
|
|
}
|
|
|
|
const vaults = new Cache('vaults') // vault:owner
|
|
// Vault
|
|
// address owner
|
|
// balances { tokenAddress: amount }
|
|
// recentOrders []
|
|
|
|
const deployerAbi = await getAbi('VaultDeployer');
|
|
|
|
|
|
function newVault(address, owner) {
|
|
return {address, owner, tokens: {}} // internal json version
|
|
}
|
|
|
|
export function vaultAddress(chainId, ownerAddress) {
|
|
const encoded = ethers.AbiCoder.defaultAbiCoder().encode(['address'], [ownerAddress])
|
|
const salt = ethers.keccak256(encoded)
|
|
return ethers.getCreate2Address(getDeployerAddress(chainId), salt, VAULT_INIT_CODE_HASH)
|
|
}
|
|
|
|
|
|
export function loginAddress(socket, chainId, address) {
|
|
// todo check for existing vault
|
|
if (!vaults[address]) {
|
|
//
|
|
} else {
|
|
// todo send welcome with basic info and extra tokens
|
|
|
|
}
|
|
}
|
|
|
|
|
|
export async function ensureVault(socket, chainId, owner) {
|
|
const address = vaultAddress(chainId, owner)
|
|
if (!vaults[address]) {
|
|
const deployer = new ethers.Contract(DEPLOYER_ADDRESS, deployerAbi, getSigner(chainId))
|
|
await deployer.deployVault(owner)
|
|
}
|
|
}
|
|
|
|
|
|
export async function watchVaultCreated(provider, db, event) {
|
|
console.log(`vault created`, event)
|
|
}
|
|
|
|
export async function watchErc20Transfer(provider, db, event) {
|
|
console.log('Transfer', event)
|
|
const [from, to, amount] = event.args
|
|
let vault = vaults[from]
|
|
let delta = 0
|
|
if (vault !== undefined)
|
|
delta = -amount
|
|
else {
|
|
vault = vaults[to]
|
|
if (vault !== undefined)
|
|
delta = amount
|
|
}
|
|
if (vault) {
|
|
let oldBalance = vault.balances[event.address]
|
|
if (oldBalance === undefined) {
|
|
|
|
}
|
|
}
|
|
}
|