Skip to content

Commit

Permalink
WIP: Siennaswap on chain (DefiLlama#7451)
Browse files Browse the repository at this point in the history
* WIP

* refactor sienna

---------

Co-authored-by: llama <[email protected]>
  • Loading branch information
g1nt0ki and llama authored Oct 23, 2023
1 parent 4dddcbf commit 45be82a
Show file tree
Hide file tree
Showing 8 changed files with 243 additions and 185 deletions.
34 changes: 28 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,15 @@
"blakejs": "^1.2.1",
"bn.js": "^5.2.1",
"borsh": "^0.7.0",
"curve25519-js": "^0.0.4",
"dotenv": "^8.6.0",
"ethers": "^5.6.5",
"graphql": "^16.6.0",
"graphql-request": "^4.0.0",
"hi-base32": "^0.5.1",
"js-sha512": "^0.8.0",
"limiter": "2.1.0",
"miscreant": "^0.3.2",
"p-limit": "^3.1.0",
"starknet": "^4.17.1",
"tron-format-address": "^0.1.8",
Expand Down
60 changes: 0 additions & 60 deletions projects/helper/CosmWasm.js

This file was deleted.

72 changes: 72 additions & 0 deletions projects/helper/chain/secret.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const { endPoints } = require('./cosmos');
const EnigmaUtils = require('../utils/enigma')
const host = endPoints.secret
const { toBase64, fromBase64, fromUtf8, } = EnigmaUtils
const axios = require('axios')
let client

function getClient() {
if (!client) client = new SecretClient(host)
return client
}

async function queryContract({ contract, data, } = {}) {
return getClient().queryContractSmart({contract, data,})
}
async function getContracts(codeId) {
return getClient().getContracts(codeId)
}


module.exports = {
queryContract,
getContracts,
}

class SecretClient {
constructor(nodeURL) {
this.nodeURL = nodeURL
this.codeHashes = {}
this.enigmautils = new EnigmaUtils(nodeURL)
}

async getContracts(codeId) {
console.log('getContracts', codeId)
const path = `/compute/v1beta1/contracts/${codeId}`;
const { contract_infos } = (await this.get(path));
return contract_infos.map(({ contract_address, ContractInfo: { code_id, creator, label } }) => ({
address: contract_address,
code_id, creator, label,
}));
}

async queryContractSmart({ contract, data }) {
const contractCodeHash = await this.getCodeHashByContractAddr(contract);
const encrypted = await this.enigmautils.encrypt(contractCodeHash, data);
const nonce = encrypted.slice(0, 32);
const encoded = toBase64(encrypted);
const path = `/compute/v1beta1/query/${contract}`;
let responseData = (await this.get(path, { query: encoded })).data
// By convention, smart queries must return a valid JSON document (see https://github.com/CosmWasm/cosmwasm/issues/144)
return JSON.parse(fromUtf8(fromBase64(fromUtf8(await this.enigmautils.decrypt(fromBase64(responseData), nonce)))));

}

async get(api, queryParams = {}) {
const { data } = await axios.get(this.nodeURL + api, { params: queryParams })
return data
}

async getCodeHashByContractAddr(contract) {
if (!this.codeHashes[contract])
this.codeHashes[contract] = fetchCodeHash(this)

return this.codeHashes[contract]

async function fetchCodeHash(obj) {
const { code_hash } = await obj.get(`/compute/v1beta1/code_hash/by_contract_address/${contract}`)
return code_hash
}
}

}
3 changes: 2 additions & 1 deletion projects/helper/utils/enigma.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class EnigmaUtils {
// const txEncryptionIkm = curve25519.sharedKey(this.privkey, consensusIoPubKey);
// const txEncryptionKey = crypto.hkdfSync("sha256", Uint8Array.from([...txEncryptionIkm, ...nonce]), hkdfSalt, '', 32)
// const { key: txEncryptionKey } = await hkdf.compute(Uint8Array.from([...txEncryptionIkm, ...nonce]), "SHA-256", 32, "", hkdfSalt)
// console.log(txEncryptionKey, 'txEncryptionKey', new Uint8Array(txEncryptionKey))
const txEncryptionKey = fakeKey
return new Uint8Array(txEncryptionKey)
}
Expand Down Expand Up @@ -115,4 +116,4 @@ EnigmaUtils.toBase64 = toBase64

module.exports = EnigmaUtils

const fakeKey = new Uint8Array([104, 52, 184, 163, 49, 137, 219, 71, 54, 99, 223, 160, 48, 83, 58, 92, 175, 118, 60, 103, 134, 11, 44, 191, 210, 206, 164, 120, 48, 100, 9, 130]).buffer
const fakeKey = new Uint8Array([248, 24, 153, 160, 20, 71, 22, 226, 185, 239, 57, 17, 11, 65, 67, 231, 36, 199, 102, 223, 164, 45, 133, 137, 223, 33, 119, 169, 155, 169, 194, 224]).buffer
94 changes: 94 additions & 0 deletions projects/sienna-lend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const { queryContract, } = require('../helper/chain/secret')
const { PromisePool } = require('@supercharge/promise-pool')

const LEND_OVERSEER_CONTRACT = "secret1pf88n9hm64mn58aw48jxfs2fsvzr07svnrrdlv";

let lendingMarkets = null

async function getLendMarkets() {
if (!lendingMarkets) lendingMarkets = _get()
return lendingMarkets

async function _get() {
let markets = [], hasMore = true, start = 0, limit = 30

while (hasMore) {
const { entries, total } = await queryContract({
contract: LEND_OVERSEER_CONTRACT, data: {
markets: {
pagination: {
limit: 30,
start
}
}
}
});
start += limit
hasMore = total > start
markets = markets.concat(entries.map(i => i.contract.address));
}

const data = []

const { errors } = await PromisePool.withConcurrency(5)
.for(markets)
.process(async (addr) => {

let { total_borrows, total_supply, } = await queryContract({ contract: addr, data: { state: {} } })
let exchange_rate = await queryContract({ contract: addr, data: { exchange_rate: {} } })
const { address } = await queryContract({ contract: addr, data: { underlying_asset: {} } })
// const { token_info: { decimals }} = await queryContract({ contract: address, data: { token_info: {} } })
const scale = exchange_rate
data.push({ address, total_borrows: total_borrows * scale, total_supply: total_supply * scale })
})

if (errors && errors.length)
throw errors[0]

return data
}

}

async function tvl(_, _b, _cb, { api, }) {
const data = await getLendMarkets()
data.forEach(i => {
api.add(i.address, i.total_supply - i.total_borrows)
})

return api.getBalances()
}

async function borrowed(_, _b, _cb, { api, }) {
const data = await getLendMarkets()
data.forEach(i => {
api.add(i.address, i.total_borrows)
})


return api.getBalances()
}

async function staking(_, _b, _cb, { api, }) {
const SIENNA_SINGLE_SIDED_POOLS = [
{ address: "secret1ja57vrpqusx99rgvxacvej3vhzhh4rhlkdkd7w", version: 1 },
{ address: "secret109g22wm3q3nfys0v6uh7lqg68cn6244n2he4t6", version: 2 },
{ address: "secret1uta9zf3prn7lvc6whp8sqv7ynxmtz3jz9xkyu7", version: 3 }
];

const SIENNA_TOKEN_ADDRESS = "secret1rgm2m5t530tdzyd99775n6vzumxa5luxcllml4";
await Promise.all(SIENNA_SINGLE_SIDED_POOLS.map(async ({ address, version }) => {
if (version === 3) {
const fetchedPool = await queryContract({ contract: address, data: { rewards: { pool_info: { at: new Date().getTime() } } } });
api.add('sienna', fetchedPool.rewards.pool_info.staked / 1e18, { skipChain: true })
} else {
const fetchedPool = await queryContract({ contract: address, data: { pool_info: { at: new Date().getTime() } } });
api.add('sienna', fetchedPool.pool_info.pool_locked / 1e18, { skipChain: true })
}
}));
return api.getBalances()
}

module.exports = {
secret: { tvl, borrowed, staking, }
}
Loading

0 comments on commit 45be82a

Please sign in to comment.