Skip to content

Commit

Permalink
instead of a viem client instance just use a sign function more generic.
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronmgdr committed Sep 25, 2024
1 parent d2091b6 commit 838939b
Show file tree
Hide file tree
Showing 19 changed files with 194 additions and 215 deletions.
2 changes: 0 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@
"--inspect-brk",
"${workspaceRoot}/node_modules/.bin/jest",
"--rootDir",
"${workspaceFolder}/packages/contractkit",
"--runInBand",
"${workspaceFolder}/packages/contractkit/src/**/*.test.ts",
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ We've made a mini-series to explain you:

## 🧑‍💻 Quickstart

The following steps use the Celo [ContractKit](https://docs.celo.org/developer/contractkit) to quickly set you up to play around with the protocol. If you would like to use a different library instead, please refer to the [example scripts](examples/).
The following steps use the [Viem](https://viem.sh) to quickly set you up to play around with the protocol. If you would like to use a different library instead, please refer to the [example scripts](examples/).

1. Add the [`@celo/identity`](https://www.npmjs.com/package/@celo/identity) package into your project.

Expand Down Expand Up @@ -80,7 +80,7 @@ The following steps use the Celo [ContractKit](https://docs.celo.org/developer/c
// authSigner provides information needed to authenticate with ODIS
const authSigner: AuthSigner = {
authenticationMethod: OdisUtils.Query.AuthenticationMethod.WALLET_KEY,
contractKit: kit,
sign191: ({message, account}) => viemClient.signMessage({message, account}),
};
// serviceContext provides the ODIS endpoint and public key
const serviceContext = OdisUtils.Query.getServiceContext(
Expand Down Expand Up @@ -153,7 +153,7 @@ The following steps use the Celo [ContractKit](https://docs.celo.org/developer/c

| Type |
| :-------------------------------------------------------------------------------------------: |
| [ContractKit](docs/examples/contractKit.ts) |
| [Viem](docs/examples/viem.ts) |
| [EthersJS (v5)](docs/examples/ethers.ts) |
| [web3.js](docs/examples/web3.ts) |
| [NextJS based web app (Phone Number)](https://github.com/celo-org/emisianto) |
Expand All @@ -162,7 +162,7 @@ The following steps use the Celo [ContractKit](https://docs.celo.org/developer/c
| [NextJS based web app (Twitter)](https://github.com/celo-org/SocialConnect-Twitter) |
| [Server side NextJS (Twitter)](https://github.com/celo-org/SocialConnect-Twitter-Server-Side) |

<!-- - [@celo/contractkit](https://docs.celo.org/developer/contractkit) (see [`examples/contractKit.ts`](examples/contractKit.ts)),
<!-- - [viem](https://viem.sh) (see [`examples/viem.ts`](examples/viem.ts)),
- [ethers.js](https://ethers.org/) (see [`examples/ethers.ts`](examples/ethers.ts)), and
- [web3.js](https://web3js.readthedocs.io/en/v1.8.1/) (see [`examples/web3.ts`](examples/web3.ts)). -->

Expand Down
20 changes: 10 additions & 10 deletions apps/combiner/test/end-to-end/pnp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { PnpClientQuotaStatus } from '@celo/identity/lib/odis/quota'
import {
CombinerEndpoint,
getAccountsContract,
getCUSDContract,
getOdisPaymentsContract,
PnpQuotaRequest,
PnpQuotaResponseSchema,
SignMessageRequest,
SignMessageResponseSchema,
} from '@celo/phone-number-privacy-common'
import { getCUSDContract } from '@celo/phone-number-privacy-common/src/celoViemKit'
import { config as signerConfig } from '@celo/phone-number-privacy-signer/src/config'
import { normalizeAddressWith0x } from '@celo/utils/lib/address'
import threshold_bls from 'blind-threshold-bls'
Expand All @@ -24,6 +24,7 @@ import {
ACCOUNT_ADDRESS,
ACCOUNT_ADDRESS_NO_QUOTA,
BLINDED_PHONE_NUMBER,
client,
dekAuthSigner,
deks,
getTestContextName,
Expand All @@ -47,7 +48,7 @@ const expectedVersion = getCombinerVersion()

describe(`Running against service deployed at ${combinerUrl} w/ blockchain provider ${fullNodeUrl}`, () => {
beforeAll(async () => {
const accountsContract = getAccountsContract(walletAuthSigner.client)
const accountsContract = getAccountsContract(client)
const dekPublicKey = normalizeAddressWith0x(deks[0].publicKey) as Hex
if ((await accountsContract.read.getDataEncryptionKey([ACCOUNT_ADDRESS])) !== dekPublicKey) {
await accountsContract.write.setAccountDataEncryptionKey([dekPublicKey], {
Expand Down Expand Up @@ -136,7 +137,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi
CombinerEndpoint.PNP_QUOTA,
PnpQuotaResponseSchema,
{
Authorization: await walletAuthSigner.client.signMessage({
Authorization: await walletAuthSigner.sign191({
message: JSON.stringify(req),
account: privateKeyToAccount(PRIVATE_KEY_NO_QUOTA),
}),
Expand Down Expand Up @@ -164,19 +165,18 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi
const amountInWei = BigInt(
signerConfig.quota.queryPriceInCUSD.times(1e18).times(numQueriesToReplenish).toString(),
)
const client = walletAuthSigner.client
const stableToken = getCUSDContract(client)
const odisPayments = getOdisPaymentsContract(client)

const sender = privateKeyToAccount(ensureLeading0x(PRIVATE_KEY))

await stableToken.write.approve([odisPayments.address, amountInWei], {
account: sender,
chain: walletAuthSigner.client.chain,
chain: client.chain,
})
await odisPayments.write.payInCUSD([ACCOUNT_ADDRESS, amountInWei], {
account: sender,
chain: walletAuthSigner.client.chain,
chain: client.chain,
})
// wait for cache to expire and then query to refresh
await sleep(5 * 1000)
Expand Down Expand Up @@ -443,10 +443,10 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi
CombinerEndpoint.PNP_SIGN,
SignMessageResponseSchema,
{
Authorization: await walletAuthSigner.client.signMessage(
JSON.stringify(req),
ACCOUNT_ADDRESS_NO_QUOTA,
),
Authorization: await client.signMessage({
message: JSON.stringify(req),
account: ACCOUNT_ADDRESS_NO_QUOTA,
}),
},
),
).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR)
Expand Down
4 changes: 2 additions & 2 deletions apps/combiner/test/end-to-end/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const CONTACT_PHONE_NUMBERS = [CONTACT_PHONE_NUMBER]
/**
* RESOURCES AND UTILS
*/
const client = createWalletClient({
export const client = createWalletClient({
transport: http(DEFAULT_FORNO_URL),
chain: celo,
account: privateKeyToAccount(PRIVATE_KEY_NO_QUOTA),
Expand Down Expand Up @@ -94,5 +94,5 @@ export const dekAuthSigner = (index: number): EncryptionKeySigner => {

export const walletAuthSigner: WalletKeySigner = {
authenticationMethod: AuthenticationMethod.WALLET_KEY,
client,
sign191: (args) => client.signMessage(args),
}
65 changes: 35 additions & 30 deletions apps/combiner/test/integration/pnp.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { newKit } from '@celo/contractkit'
import {
AuthenticationMethod,
CombinerEndpoint,
Expand Down Expand Up @@ -37,6 +36,8 @@ import { Server } from 'http'
import { Server as HttpsServer } from 'https'
import { Knex } from 'knex'
import request from 'supertest'
import { createWalletClient, http } from 'viem'
import { celoAlfajores } from 'viem/chains'
import config, { getCombinerVersion } from '../../src/config'
import { startCombiner } from '../../src/server'
import { getBlindedPhoneNumber, serverClose } from '../utils'
Expand Down Expand Up @@ -160,6 +161,7 @@ const mockContractKit = createMockContractKit({
[ContractRetrieval.getOdisPayments]: createMockOdisPayments(mockOdisPaymentsTotalPaidCUSD),
})

// TODO replace this mock with mock of viemCeloKit stuff
// Mock newKit as opposed to the CK constructor
// Returns an object of type ContractKit that can be passed into the signers + combiner
jest.mock('@celo/contractkit', () => ({
Expand Down Expand Up @@ -192,7 +194,10 @@ describe('pnpService', () => {
const message = Buffer.from('test message', 'utf8')

// In current setup, the same mocked kit is used for the combiner and signers
const mockKit = newKit('dummyKit')
const mockClient = createWalletClient({
chain: celoAlfajores,
transport: http(),
})

const sendPnpSignRequest = async (
req: SignMessageRequest,
Expand Down Expand Up @@ -284,7 +289,7 @@ describe('pnpService', () => {
[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-3`, PNP_THRESHOLD_DEV_PK_SHARE_3_V3],
]),
)
app = startCombiner(combinerConfig, mockKit)
app = startCombiner(combinerConfig, mockClient)
})

beforeEach(async () => {
Expand Down Expand Up @@ -314,9 +319,9 @@ describe('pnpService', () => {

describe('when signers are operating correctly', () => {
beforeEach(async () => {
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockKit).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, keyProvider3, mockKit).listen(3003)
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockClient).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockClient).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, keyProvider3, mockClient).listen(3003)
})

describe(`${CombinerEndpoint.PNP_QUOTA}`, () => {
Expand Down Expand Up @@ -580,7 +585,7 @@ describe('pnpService', () => {
JSON.stringify(combinerConfig),
)
configWithApiDisabled.phoneNumberPrivacy.enabled = false
const appWithApiDisabled = startCombiner(configWithApiDisabled, mockKit)
const appWithApiDisabled = startCombiner(configWithApiDisabled, mockClient)
const req = {
account: ACCOUNT_ADDRESS1,
}
Expand Down Expand Up @@ -871,7 +876,7 @@ describe('pnpService', () => {
JSON.stringify(combinerConfig),
)
configWithApiDisabled.phoneNumberPrivacy.enabled = false
const appWithApiDisabled = startCombiner(configWithApiDisabled, mockKit)
const appWithApiDisabled = startCombiner(configWithApiDisabled, mockClient)

const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1)
const res = await sendPnpSignRequest(req, authorization, appWithApiDisabled)
Expand All @@ -898,7 +903,7 @@ describe('pnpService', () => {
)
const appWithFailOpenDisabled = startCombiner(
combinerConfigWithFailOpenDisabled,
mockKit,
mockClient,
)
const res = await sendPnpSignRequest(req, authorization, appWithFailOpenDisabled)

Expand Down Expand Up @@ -927,9 +932,9 @@ describe('pnpService', () => {
const badKeyProvider1 = new MockKeyProvider(
new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare1]]),
)
signer1 = startSigner(signerConfig, signerDB1, badKeyProvider1, mockKit).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockKit).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, keyProvider3, mockKit).listen(3003)
signer1 = startSigner(signerConfig, signerDB1, badKeyProvider1, mockClient).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockClient).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, keyProvider3, mockClient).listen(3003)
})

describe(`${CombinerEndpoint.PNP_SIGN}`, () => {
Expand Down Expand Up @@ -972,9 +977,9 @@ describe('pnpService', () => {
new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare2]]),
)

signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, badKeyProvider1, mockKit).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, badKeyProvider2, mockKit).listen(3003)
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockClient).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, badKeyProvider1, mockClient).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, badKeyProvider2, mockClient).listen(3003)
})

describe(`${CombinerEndpoint.PNP_SIGN}`, () => {
Expand All @@ -997,11 +1002,11 @@ describe('pnpService', () => {
beforeEach(async () => {
const configWithApiDisabled: SignerConfig = JSON.parse(JSON.stringify(signerConfig))
configWithApiDisabled.api.phoneNumberPrivacy.enabled = false
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001)
signer2 = startSigner(configWithApiDisabled, signerDB2, keyProvider2, mockKit).listen(
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockClient).listen(3001)
signer2 = startSigner(configWithApiDisabled, signerDB2, keyProvider2, mockClient).listen(
3002,
)
signer3 = startSigner(configWithApiDisabled, signerDB3, keyProvider3, mockKit).listen(
signer3 = startSigner(configWithApiDisabled, signerDB3, keyProvider3, mockClient).listen(
3003,
)
})
Expand Down Expand Up @@ -1042,9 +1047,9 @@ describe('pnpService', () => {
beforeEach(async () => {
const configWithApiDisabled: SignerConfig = JSON.parse(JSON.stringify(signerConfig))
configWithApiDisabled.api.phoneNumberPrivacy.enabled = false
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockKit).listen(3002)
signer3 = startSigner(configWithApiDisabled, signerDB3, keyProvider3, mockKit).listen(
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockClient).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockClient).listen(3002)
signer3 = startSigner(configWithApiDisabled, signerDB3, keyProvider3, mockClient).listen(
3003,
)
})
Expand Down Expand Up @@ -1094,13 +1099,13 @@ describe('pnpService', () => {
const configWithShortTimeout: SignerConfig = JSON.parse(JSON.stringify(signerConfig))
configWithShortTimeout.timeout = testTimeoutMS
// Test this with all signers timing out to decrease possibility of race conditions
signer1 = startSigner(configWithShortTimeout, signerDB1, keyProvider1, mockKit).listen(
signer1 = startSigner(configWithShortTimeout, signerDB1, keyProvider1, mockClient).listen(
3001,
)
signer2 = startSigner(configWithShortTimeout, signerDB2, keyProvider2, mockKit).listen(
signer2 = startSigner(configWithShortTimeout, signerDB2, keyProvider2, mockClient).listen(
3002,
)
signer3 = startSigner(configWithShortTimeout, signerDB3, keyProvider3, mockKit).listen(
signer3 = startSigner(configWithShortTimeout, signerDB3, keyProvider3, mockClient).listen(
3003,
)
})
Expand Down Expand Up @@ -1223,7 +1228,7 @@ describe('pnpService', () => {
],
]),
)
app = startCombiner(combinerConfigLargerN, mockKit)
app = startCombiner(combinerConfigLargerN, mockClient)
})

let req: SignMessageRequest
Expand All @@ -1235,11 +1240,11 @@ describe('pnpService', () => {
signerDB4 = await initSignerDatabase(signerConfig, signerMigrationsPath)
signerDB5 = await initSignerDatabase(signerConfig, signerMigrationsPath)

signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockKit).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, keyProvider3, mockKit).listen(3003)
signer4 = startSigner(signerConfig, signerDB4, keyProvider4, mockKit).listen(3004)
signer5 = startSigner(signerConfig, signerDB5, keyProvider5, mockKit).listen(3005)
signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockClient).listen(3001)
signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockClient).listen(3002)
signer3 = startSigner(signerConfig, signerDB3, keyProvider3, mockClient).listen(3003)
signer4 = startSigner(signerConfig, signerDB4, keyProvider4, mockClient).listen(3004)
signer5 = startSigner(signerConfig, signerDB5, keyProvider5, mockClient).listen(3005)

userSeed = new Uint8Array(32)
for (let i = 0; i < userSeed.length - 1; i++) {
Expand Down
4 changes: 2 additions & 2 deletions apps/monitor/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export const queryOdisForQuota = async (
})
const authSigner: AuthSigner = {
authenticationMethod: OdisUtils.Query.AuthenticationMethod.WALLET_KEY,
client,
sign191: ({ message, account }) => client.signMessage({ message, account }),
}

const abortController = new AbortController()
Expand Down Expand Up @@ -188,7 +188,7 @@ async function getAuthSignerAndAccount(

authSigner = {
authenticationMethod: OdisUtils.Query.AuthenticationMethod.WALLET_KEY,
client,
sign191: client.signMessage,
}
phoneNumber = defaultPhoneNumber.value()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { getDataEncryptionKey, getOdisPaymentsContract } from '@celo/phone-numbe
import { BigNumber } from 'bignumber.js'
import Logger from 'bunyan'
import { Address, Client, Hex } from 'viem'
import { config } from '../../config'
import { Counters, Histograms, newMeter } from '../metrics'
import { config } from '../config'
import { Counters, Histograms, newMeter } from './metrics'

export async function getOnChainOdisPayments(
client: Client,
Expand All @@ -16,7 +16,6 @@ export async function getOnChainOdisPayments(
retryAsyncWithBackOffAndTimeout(
async () => {
const paid = await getOdisPaymentsContract(client).read.totalPaidCUSD([account])
// might replace bigNumber with big int but not yet
return new BigNumber(paid.toString(10))
},
config.fullNodeRetryCount,
Expand Down
2 changes: 1 addition & 1 deletion apps/signer/src/pnp/services/account-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import BigNumber from 'bignumber.js'
import Logger from 'bunyan'
import { LRUCache } from 'lru-cache'
import { Address, WalletClient } from 'viem'
import { getDEK, getOnChainOdisPayments } from '../../common/contracts'
import { OdisError, wrapError } from '../../common/error'
import { traceAsyncFunction } from '../../common/tracing-utils'
import { getDEK, getOnChainOdisPayments } from '../../common/web3/contracts'
import { config } from '../../config'

export interface PnpAccount {
Expand Down
Loading

0 comments on commit 838939b

Please sign in to comment.